﻿using HalconDotNet;
using Halcon二次开发.Model.储存每个Controller的单例对象;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Halcon二次开发.Controller.Controller基类;
using Halcon二次开发.Model;
using Halcon二次开发.Model.储放所有单例.储存每个单例界面;
using Halcon二次开发.Model.工具区域的扩展类;
using System.Windows.Shapes;
using static System.Windows.Forms.LinkLabel;
using System.Diagnostics;
using System.Windows.Forms;
using System.IO;
using Halcon二次开发.View.卡尺;
using Halcon二次开发.Tools;
using Halcon二次开发.Model.自定义控件;
using Halcon二次开发.View.图片显示弹窗;
using System.Reflection;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.ToolTip;
using Sunny.UI.Win32;
using System.Linq.Expressions;
using System.Windows.Forms.VisualStyles;
using System.Windows.Media.Media3D;
using System.Data;

namespace Halcon二次开发.Controller.卡尺
{
    /// <summary>
    /// 精准测量卡尺
    /// </summary>
    public class Caliper
    {
        /// <summary>
        /// 该工具的线段对象
        /// </summary>
        List<HDrawingObjectEx> lines = new List<HDrawingObjectEx>();
        /// <summary>
        /// 卡尺界面
        /// </summary>
        PreciseCaliper form;
        /// <summary>
        /// 卡尺校验保存数据
        /// </summary>
        public string path;
        //HTuple hv_Row, hv_Column, hv_Phi, hv_Length1, hv_Length2;
        HObject ho_ROI_1;
        /// <summary>
        /// 该工具的线段对象
        /// </summary>
        HDrawingObjectEx line;
        /// <summary>
        /// 当前控件对象
        /// </summary>
        public HSmartWindowControl hw;

        /// 移动事件更改数据禁止
        /// </summary>
        bool check = false;
        /// <summary>
        /// 有没有放置
        /// </summary>
        bool putCheck = false;
        /// <summary>
        /// 模式选择
        /// </summary>
        ComboBox combox1;

        /// <summary>
        /// 位置-旋转-长度1-长度2
        /// </summary>
        NumericUpDown numericUpDown1, numericUpDown2, numericUpDown3, numericUpDown7, numericUpDown10;

        /// <summary>
        /// 标注图形,用于第一次画显示在模板的第一个元素上面
        /// </summary>
        public HObject ho_Biaozhu;

        /// <summary>
        /// 偏移量 - 第一个模板的数据  第一个绘制的线段数据 
        /// </summary>
        public double firstModel_y, firstModel_x, firstModel_phi;
        #region 控制参数
        /// <summary>
        /// 输入图像
        /// </summary>
        public HObject HideIntputImage;
        /// <summary>
        /// 输入的行-列-角度 坐标
        /// </summary>
        public double[] HideIntputArrayRows, HideIntputArrayColumns, HideIntputArrayPhis;
        /// <summary>
        /// 卡尺的位置  - 输出点 - 距离 
        /// </summary>
        public double HideIntputX, HideIntputY, HideIntputPhi, HideIntputLength1, HideIntputLength2, HideOutputX1, HideOutputY1, HideOutputX2, HideOutputY2;
        /// <summary>
        /// 输出的距离数组
        /// </summary>
        public double[] HideOutputArrayDistances;

        /// <summary>
        /// 卡尺的宽度,高度,对比度,平滑度
        /// </summary>
        public double HideIntputWidth = 0, HideIntputHeight = 0, HideIntputThreshold, HideIntputSigma;
        /// <summary>
        /// 颜色样式
        /// </summary>
        public string HideOutputBorderColor, HideOutputCenterConlor, HideOutputlineColor = "blue";
        //输出结果
        public Dictionary<HObject, bool> HideOutputResults = new Dictionary<HObject, bool>();
        //中心的row，column坐标
        public double[] HideOutputArrayRows, HideOutputArrayColumns;
        /// <summary>
        /// 所有线段的2个点的集合，二维数组
        /// </summary>
        public double[,] linesList;

        public HwindowFlowNodeUrseControl hwindowFlowNode;
        #endregion
        public Caliper(string path, PreciseCaliper form, HwindowFlowNodeUrseControl hwindowFlowNode)
        {
            //获取当前工位
            hw = hwindowFlowNode.hSmartWindowControl1;
            this.hwindowFlowNode = hwindowFlowNode;
            this.path = path;
            this.form = form;
        }

        public Caliper()
        {
        }
        /// <summary>
        /// 运行
        /// </summary>
        public void Run()
        {
            if (HideIntputImage == null)
            {
                throw new Exception("当前输入图像为空!");
            }
            //先清除原本的Dataview集合
            form.dataGridView1.Rows.Clear();
            if (form.comboBox3.Text == "找线功能")
            {
                Line1ToLine2();
            }
            else if (form.comboBox3.Text == "找点功能")
            {
                //找点功能方法
                Point1Point2Run();
            }
        }
        /// <summary>
        /// 工具的单次运行
        /// </summary>
        public void Tool_Run()
        {

            if (HideIntputImage == null)
            {
                throw new Exception("当前图像为空");
            }
            try
            {
                hw.HalconWindow.ClearWindow();
                HOperatorSet.DispObj(HideIntputImage, hw.HalconWindow);
            }
            catch (Exception e) { throw new Exception("取像失败"); };
            Run();
        }

        //线段1的对象
        public HTuple[] line1Place = new HTuple[] { 100, 0, 100, 200 };//线段1位置
        public HDrawingObject line1Object;//线段1的对象
        //线段2的对象
        public HTuple[] line2Place = new HTuple[] { 200, 0, 200, 200 };//线段2位置
        public HDrawingObject line2Object;//线段2的对象
        /// <summary>
        /// 线到线功能的使用开始
        /// </summary>
        public void DrawLineToLine()
        {
            //HOperatorSet.ClearWindow(hw.HalconWindow);
            //HOperatorSet.DispObj(HideIntputImage, hw.HalconWindow);

            //line1Place = new HTuple[] { double.Parse(form.caliper1Row1.Value + ""), double.Parse(form.caliper1Col1.Value + ""), double.Parse(form.caliper1Row2.Value + ""), double.Parse(form.caliper1Col2.Value + "") };
            //line2Place = new HTuple[] { double.Parse(form.caliper2Row1.Value + ""), double.Parse(form.caliper2Col1.Value + ""), double.Parse(form.caliper2Row2.Value + ""), double.Parse(form.caliper2Col2.Value + "") };

            ////线段1的对象生成
            //line1Object = HDrawingObject.CreateDrawingObject(HDrawingObject.HDrawingObjectType.LINE, line1Place);
            ////线段2的对象生成
            //line2Object = HDrawingObject.CreateDrawingObject(HDrawingObject.HDrawingObjectType.LINE, line2Place);

            ////生成一个目标位置
            //HOperatorSet.SetDraw(hwindowFlowNode.hSmartWindowControl1.HalconWindow, "fill");
            //HOperatorSet.SetColor(hwindowFlowNode.hSmartWindowControl1.HalconWindow, "blue");
            //HOperatorSet.GenCircle(out HObject circle, HideIntputArrayRows[0], HideIntputArrayColumns[0], 20);
            //HOperatorSet.DispObj(circle, hwindowFlowNode.hSmartWindowControl1.HalconWindow);
            //HOperatorSet.SetDraw(hwindowFlowNode.hSmartWindowControl1.HalconWindow, "margin");
            //HOperatorSet.SetColor(hwindowFlowNode.hSmartWindowControl1.HalconWindow, "green");
            ////为线段1注册事件
            ////线段拖动触发事件注册
            //line1Object.OnDrag(LineOnDrag1);
            ////线段长度修改触发事件注册
            //line1Object.OnResize(LineOnResize1);
            ////为线段2注册事件
            ////线段拖动触发事件注册
            //line2Object.OnDrag(LineOnDrag2);
            ////线段长度修改触发事件注册
            //line2Object.OnResize(LineOnResize2);
            //line1Object.SetDrawingObjectParams("color", "green");
            //line2Object.SetDrawingObjectParams("color", "blue");
            ////将2个线段显示在窗口上
            //hw.HalconWindow.AttachDrawingObjectToWindow(line2Object);
            //hw.HalconWindow.AttachDrawingObjectToWindow(line1Object);
        }
        /// <summary>
        /// 1线段长度修改触发事件
        /// </summary>
        /// <param name="drawid"></param>
        /// <param name="window"></param>
        /// <param name="type"></param>
        /// <exception cref="NotImplementedException"></exception>
        private void LineOnResize1(HDrawingObject drawid, HWindow window, string type)
        {
            UpdataDrawingObjecDatLine1(drawid);
        }
        /// <summary>
        /// 1线段拖动触发事件
        /// </summary>
        /// <param name="drawid"></param>
        /// <param name="window"></param>
        /// <param name="type"></param>
        /// <exception cref="NotImplementedException"></exception>
        private void LineOnDrag1(HDrawingObject drawid, HWindow window, string type)
        {
            UpdataDrawingObjecDatLine1(drawid);
        }
        /// <summary>
        /// 1线段长度修改触发事件
        /// </summary>
        /// <param name="drawid"></param>
        /// <param name="window"></param>
        /// <param name="type"></param>
        /// <exception cref="NotImplementedException"></exception>
        private void LineOnResize2(HDrawingObject drawid, HWindow window, string type)
        {
            UpdataDrawingObjecDatLine2(drawid);
        }
        /// <summary>
        /// 1线段拖动触发事件
        /// </summary>
        /// <param name="drawid"></param>
        /// <param name="window"></param>
        /// <param name="type"></param>
        /// <exception cref="NotImplementedException"></exception>
        private void LineOnDrag2(HDrawingObject drawid, HWindow window, string type)
        {
            UpdataDrawingObjecDatLine2(drawid);
        }
        //线1的第一次模板的数据
        public List<double> line1counterFrist;
        /// <summary>
        /// 线段1线段修改具体实现
        /// </summary>
        private void UpdataDrawingObjecDatLine1(HDrawingObject drawid)
        {
            //try
            //{
            //    (FormDb.Db["Form1"] as Form1).Cursor = Cursors.Cross;
            //    //创建一个要得到对象属性的元组
            //    var attTuple = new HTuple("row1", "column1", "row2", "column2");
            //    //获取对应的属性
            //    var valueTuple = drawid.GetDrawingObjectParams(attTuple);
            //    //对对应的属性进行封装一下,后面好加入到集合中
            //    line1Place = new HTuple[] { valueTuple[0], valueTuple[1], valueTuple[2], valueTuple[3] };

            //    form.caliper1Row1.Value = decimal.Parse(valueTuple[0].D + "");
            //    form.caliper1Col1.Value = decimal.Parse(valueTuple[1].D + "");
            //    form.caliper1Row2.Value = decimal.Parse(valueTuple[2].D + "");
            //    form.caliper1Col2.Value = decimal.Parse(valueTuple[3].D + "");
            //    line1counterFrist = new List<double>();
            //    List<double> line1Doubles = new List<double>();
            //    //记录第一次模板的位置
            //    line1counterFrist.Add(HideIntputArrayRows[0]);
            //    line1counterFrist.Add(HideIntputArrayColumns[0]);
            //    line1counterFrist.Add(HideIntputArrayPhis[0]);
            //    //保存线段数据
            //    line1Doubles.Add(valueTuple[0]);
            //    line1Doubles.Add(valueTuple[1]);
            //    line1Doubles.Add(valueTuple[2]);
            //    line1Doubles.Add(valueTuple[3]);
            //    //将这个基准数据进行保存
            //    string path = $@"Data\工程文件\{hwindowFlowNode.projectName}\{hwindowFlowNode.name}任务文件\精准测量工具卡尺校验数据\{form.nodeName}\测量线1基准数据";
            //    if (Directory.Exists(path))
            //    {
            //        Directory.Delete(path, true);
            //    }
            //    Directory.CreateDirectory(path);
            //    HelpJsons.Write<double>(line1counterFrist, path + "\\线1线段模板基准数据.json");
            //    HelpJsons.Write<double>(line1Doubles, path + "\\线段1点位数据.json");
            //}
            //catch (Exception ex)
            //{
            //    (FormDb.Db["Form1"] as Form1).textBox1.AppendText("线1移动时失败" + ":" + ex.Message + "\r\n");
            //}
        }
        //线2的第一次模板的数据
        public List<double> line2counterFrist;
        /// <summary>
        ///  线段2线段修改具体实现
        /// </summary>
        private void UpdataDrawingObjecDatLine2(HDrawingObject drawid)
        {
            //try
            //{
            //    (FormDb.Db["Form1"] as Form1).Cursor = Cursors.Cross;
            //    //创建一个要得到对象属性的元组
            //    var attTuple = new HTuple("row1", "column1", "row2", "column2");
            //    //获取对应的属性
            //    var valueTuple = drawid.GetDrawingObjectParams(attTuple);
            //    //对对应的属性进行封装一下,后面好加入到集合中
            //    line2Place = new HTuple[] { valueTuple[0], valueTuple[1], valueTuple[2], valueTuple[3] };
            //    line2counterFrist = new List<double>();
            //    List<double> line2Doubles = new List<double>();
            //    //记录第一次模板的位置
            //    line2counterFrist.Add(HideIntputArrayRows[0]);
            //    line2counterFrist.Add(HideIntputArrayColumns[0]);
            //    line2counterFrist.Add(HideIntputArrayPhis[0]);

            //    form.caliper2Row1.Value = decimal.Parse(valueTuple[0].D + "");
            //    form.caliper2Col1.Value = decimal.Parse(valueTuple[1].D + "");
            //    form.caliper2Row2.Value = decimal.Parse(valueTuple[2].D + "");
            //    form.caliper2Col2.Value = decimal.Parse(valueTuple[3].D + "");

            //    //保存线段数据
            //    line2Doubles.Add(valueTuple[0]);
            //    line2Doubles.Add(valueTuple[1]);
            //    line2Doubles.Add(valueTuple[2]);
            //    line2Doubles.Add(valueTuple[3]);
            //    //将这个基准数据进行保存
            //    string path = $@"Data\工程文件\{hwindowFlowNode.projectName}\{hwindowFlowNode.name}任务文件\精准测量工具卡尺校验数据\{form.nodeName}\测量线2基准数据";
            //    if (Directory.Exists(path))
            //    {
            //        Directory.Delete(path, true);
            //    }
            //    Directory.CreateDirectory(path);
            //    HelpJsons.Write<double>(line2counterFrist, path + "\\线2线段模板基准数据.json");
            //    HelpJsons.Write<double>(line2Doubles, path + "\\线段2点位数据.json");
            //}
            //catch (Exception ex)
            //{
            //    (FormDb.Db["Form1"] as Form1).textBox1.AppendText("线2移动时失败" + ":" + ex.Message + "\r\n");
            //}
        }
        /// <summary>
        /// 线与线之间的距离
        /// </summary>
        /// <exception cref="Exception"></exception>
        private void Line1ToLine2()
        {
    //        //这里要运行线与线的卡尺测量了
    //        if (HideIntputArrayColumns != null)
    //        {
    //            //卡尺卡的距离
    //            HideOutputArrayDistances = new double[HideIntputArrayColumns.Length];
    //            try
    //            {
    //                form.dataGridView1.Rows.Clear();
    //                form.line1DataGridView.Rows.Clear();
    //                linesList = new double[HideIntputArrayColumns.Length, 4];
    //                HideOutputArrayRows = new double[HideIntputArrayColumns.Length];
    //                HideOutputArrayColumns = new double[HideIntputArrayColumns.Length];
    //                if (line1counterFrist == null)
    //                {
    //                    line1counterFrist = HelpJsons.Read<double>(path + "\\" + "测量线1基准数据" + "\\线1线段模板基准数据.json");
    //                }
    //                if (line2counterFrist == null)
    //                {
    //                    line2counterFrist = HelpJsons.Read<double>(path + "\\" + "测量线2基准数据" + "\\线2线段模板基准数据.json");
    //                }
    //                for (int i = 0; i < HideIntputArrayColumns.Length; i++)
    //                {
    //                    //创建线1的对象
    //                    HOperatorSet.GenRegionLine(out HObject hLine1, double.Parse(form.caliper1Row1.Value + ""), double.Parse(form.caliper1Col1.Value + ""), double.Parse(form.caliper1Row2.Value + ""), double.Parse(form.caliper1Col2.Value + ""));
    //                    //生成第一条跟随的线
    //                    HObject ho_RegionAffineTrans1 = UtiyHalcon.MatrixCalculate(hLine1, HideIntputArrayRows[i], HideIntputArrayColumns[i], HideIntputArrayPhis[i], line1counterFrist[0], line1counterFrist[1], line1counterFrist[2]);
    //                    HOperatorSet.GetRegionPoints(ho_RegionAffineTrans1, out HTuple hv_Rows1, out HTuple hv_Columns1);
    //                    if (hv_Rows1.Length == 0)
    //                    {
    //                        HideOutputArrayDistances[i] = 0;
    //                        continue;
    //                    }
    //                    //创建计量模型，进行找线
    //                    HOperatorSet.CreateMetrologyModel(out HTuple hv_MetrologyHandle);
    //                    //下标
    //                    HTuple indexMaxPoint1 = 0;
    //                    HTuple indexMinPoint1 = 0;
    //                    if (form.comboBox2.Text == "上下排序")
    //                    {
    //                        HOperatorSet.TupleMax(hv_Columns1, out HTuple maxPoint1);
    //                        HOperatorSet.TupleFind(hv_Columns1, maxPoint1, out indexMaxPoint1);
    //                        HOperatorSet.TupleMin(hv_Columns1, out HTuple minPoint1);
    //                        HOperatorSet.TupleFind(hv_Columns1, minPoint1, out indexMinPoint1);

    //                    }
    //                    else if (form.comboBox2.Text == "左右排序")
    //                    {
    //                        HOperatorSet.TupleMax(hv_Rows1, out HTuple maxPoint1);
    //                        HOperatorSet.TupleFind(hv_Rows1, maxPoint1, out indexMaxPoint1);
    //                        HOperatorSet.TupleMin(hv_Rows1, out HTuple minPoint1);
    //                        HOperatorSet.TupleFind(hv_Rows1, minPoint1, out indexMinPoint1);
    //                    }

    //                    // 创建用于测量的计量模型
    //                    double[] hTuple = new double[]
    //                    {
    //hv_Rows1[indexMaxPoint1], hv_Columns1[indexMaxPoint1],
    //hv_Rows1[indexMinPoint1], hv_Columns1[indexMinPoint1]
    //                    };
    //                    HOperatorSet.AddMetrologyObjectGeneric(hv_MetrologyHandle, "line", hTuple, (int)form.line1HeightBox.Value, (int)form.line1Width.Value, double.Parse(form.line1muscle.Value + ""), double.Parse(form.line1contrast.Value + ""), new HTuple(), new HTuple(), out HTuple hv_Index);
    //                    string polarity = "";
    //                    if (form.line1Combox.Text == "由明向暗")
    //                    {
    //                        polarity= "negative";
    //                    }
    //                    if (form.line1Combox.Text == "由暗向明")
    //                    {
    //                        polarity = "positive";
    //                    }
    //                    else
    //                    {
    //                        polarity = "all";
    //                    }
    //                    //设置极性
    //                    HOperatorSet.SetMetrologyObjectParam(hv_MetrologyHandle, "all", "measure_transition", polarity);
    //                    //卡尺的数量
    //                    HOperatorSet.SetMetrologyObjectParam(hv_MetrologyHandle, "all", "num_measures", (int)form.line1NumberBox.Value);
    //                    //卡尺卡的数量 接受的结果数
    //                    HOperatorSet.SetMetrologyObjectParam(hv_MetrologyHandle, "all", "num_instances", 1);
    //                    //bilinear
    //                    HOperatorSet.SetMetrologyObjectParam(hv_MetrologyHandle, "all", "measure_interpolation", "bicubic");
    //                    HOperatorSet.SetMetrologyObjectParam(hv_MetrologyHandle, "all", "measure_select", "all");
    //                    //最小分数
    //                    HOperatorSet.SetMetrologyObjectParam(hv_MetrologyHandle, "all", "min_score", double.Parse(form.line1small.Value.ToString()));
    //                    //开始抓
    //                    HOperatorSet.ApplyMetrologyModel(HideIntputImage, hv_MetrologyHandle);
    //                    HOperatorSet.GetMetrologyObjectMeasures(out HObject ho_Contours, hv_MetrologyHandle, "all", "all",
    //                                out HTuple hv_Row, out HTuple hv_Column);
    //                    //HOperatorSet.GenRegionLine(out HObject regionLine1, hv_Row[0], hv_Column[0], hv_Row[hv_Row.Length - 1], hv_Column[hv_Column.Length - 1]);
    //                    HOperatorSet.GenContourPolygonXld(out HObject regionLines1, new double[] { hv_Row[0].D, hv_Row[hv_Row.Length - 1].D }, new double[] { hv_Column[0].D, hv_Column[hv_Column.Length - 1].D });
    //                    //清除线段显示
    //                    if (line1Object != null)
    //                    {
    //                        line1Object.ClearDrawingObject();
    //                    }

    //                    //创建线2的对象
    //                    HOperatorSet.GenRegionLine(out HObject hLine2, double.Parse(form.caliper2Row1.Value + ""), double.Parse(form.caliper2Col1.Value + ""), double.Parse(form.caliper2Row2.Value + ""), double.Parse(form.caliper2Col2.Value + ""));
    //                    //生成第一条跟随的线
    //                    HObject ho_RegionAffineTrans2 = UtiyHalcon.MatrixCalculate(hLine2, HideIntputArrayRows[i], HideIntputArrayColumns[i], HideIntputArrayPhis[i], line2counterFrist[0], line2counterFrist[1], line2counterFrist[2]);
    //                    HOperatorSet.GetRegionPoints(ho_RegionAffineTrans2, out HTuple hv_Rows2, out HTuple hv_Columns2);
    //                    if (hv_Rows2.Length == 0)
    //                    {
    //                        continue;
    //                    }
    //                    //创建计量模型，进行找线
    //                    HOperatorSet.CreateMetrologyModel(out HTuple hv_MetrologyHandle2);
    //                    //增加一个矩形的计量模型    这里修改了，硬触发记得同步修改
    //                    //下标
    //                    HTuple indexMaxPoint2 = 0;
    //                    HTuple indexMinPoint2 = 0;
    //                    if (form.comboBox2.Text == "上下排序")
    //                    {

    //                        HOperatorSet.TupleMax(hv_Columns2, out HTuple maxPoint2);
    //                        HOperatorSet.TupleFind(hv_Columns2, maxPoint2, out indexMaxPoint2);
    //                        HOperatorSet.TupleMin(hv_Columns2, out HTuple minPoint2);
    //                        HOperatorSet.TupleFind(hv_Columns2, minPoint2, out indexMinPoint2);
    //                    }
    //                    else if (form.comboBox2.Text == "左右排序")
    //                    {


    //                        HOperatorSet.TupleMax(hv_Rows2, out HTuple maxPoint2);
    //                        HOperatorSet.TupleFind(hv_Rows2, maxPoint2, out indexMaxPoint2);
    //                        HOperatorSet.TupleMin(hv_Rows2, out HTuple minPoint2);
    //                        HOperatorSet.TupleFind(hv_Rows2, minPoint2, out indexMinPoint2);
    //                    }

    //                    // 创建用于测量的计量模型
    //                    double[] hTuple2 = new double[]
    //                    {
    //hv_Rows2[indexMaxPoint2], hv_Columns2[indexMaxPoint2],
    //hv_Rows2[indexMinPoint2], hv_Columns2[indexMinPoint2]
    //                    };

    //                    HOperatorSet.AddMetrologyObjectGeneric(hv_MetrologyHandle2, "line", hTuple2, (int)form.line2HeightBox.Value, (int)form.line2Width.Value, double.Parse(form.line2muscle.Value + ""), double.Parse(form.line2contrast.Value + ""), new HTuple(), new HTuple(), out HTuple hv_Index2);
    //                    string polarity2 = "";
    //                    if (form.line2Combox.Text == "由明向暗")
    //                    {
    //                        polarity2 = "negative";
    //                    }
    //                    if (form.line2Combox.Text == "由暗向明")
    //                    {
    //                        polarity2 = "positive";
    //                    }else
    //                    {
    //                        polarity2 = "all";
    //                    }
    //                    //设置极性
    //                    HOperatorSet.SetMetrologyObjectParam(hv_MetrologyHandle2, "all", "measure_transition", polarity2);
    //                    //卡尺的数量
    //                    HOperatorSet.SetMetrologyObjectParam(hv_MetrologyHandle2, "all", "num_measures", (int)form.line2NumberBox.Value);
    //                    //卡尺卡的数量 接受的结果数
    //                    HOperatorSet.SetMetrologyObjectParam(hv_MetrologyHandle2, "all", "num_instances", 1);
    //                    //bilinear
    //                    HOperatorSet.SetMetrologyObjectParam(hv_MetrologyHandle2, "all", "measure_interpolation", "bicubic");
    //                    HOperatorSet.SetMetrologyObjectParam(hv_MetrologyHandle2, "all", "measure_select", "all");
    //                    //最小分数
    //                    HOperatorSet.SetMetrologyObjectParam(hv_MetrologyHandle2, "all", "min_score", double.Parse(form.line2small.Value.ToString()));
    //                    //开始抓
    //                    HOperatorSet.ApplyMetrologyModel(HideIntputImage, hv_MetrologyHandle2);
    //                    HOperatorSet.GetMetrologyObjectMeasures(out HObject ho_Contours2, hv_MetrologyHandle2, "all", "all",
    //                                out HTuple hv_Row2, out HTuple hv_Column2);
    //                    HOperatorSet.GenContourPolygonXld(out HObject regionLines2, new double[] { hv_Row2[0].D, hv_Row2[hv_Row2.Length - 1].D }, new double[] { hv_Column2[0].D, hv_Column2[hv_Column2.Length - 1].D });
    //                    //效果显示
    //                    if (form.comboBox4.Text=="开启")
    //                    {
    //                        HOperatorSet.SetColor(hw.HalconWindow,"green");
    //                        HOperatorSet.GenCrossContourXld(out HObject cross1, hv_Row,hv_Column, double.Parse(form.pigBox.Text), new HTuple(45).TupleRad());
    //                        HOperatorSet.DispObj(cross1,hw.HalconWindow);
    //                        HOperatorSet.DispObj(regionLines1, hw.HalconWindow);
    //                        HOperatorSet.SetColor(hw.HalconWindow, "blue");
    //                        HOperatorSet.GenCrossContourXld(out HObject cross2, hv_Row2, hv_Column2, double.Parse(form.pigBox.Text), new HTuple(45).TupleRad());
    //                        HOperatorSet.DispObj(cross2, hw.HalconWindow);
    //                        HOperatorSet.DispObj(regionLines2, hw.HalconWindow);
    //                        HOperatorSet.SetColor(hw.HalconWindow, "green");
    //                    }
    //                    if (line2Object != null)
    //                    {
    //                        line2Object.ClearDrawingObject();
    //                    }

    //                    //点的位置
    //                    double midRow1 = 0;
    //                    double midCol1 = 0;
    //                    //计算它是选择是那个点
    //                    if (form.comboBox1.Text == "中间距离")
    //                    {
    //                        // 7. 计算线段1的中点
    //                        midRow1 = (hv_Row[0].D + hv_Row[hv_Row.Length - 1].D) / 2;
    //                        midCol1 = (hv_Column[0].D + hv_Column[hv_Column.Length - 1].D) / 2;
    //                    }
    //                    else
    //                    {
    //                        // 初始化最小和最大距离，以及对应的索引
    //                        double minDistance = double.MaxValue;
    //                        double maxDistance = double.MinValue;
    //                        int minIndex = -1;
    //                        int maxIndex = -1;
    //                        for (int ii = 0; ii < hv_Row.Length; ii++)
    //                        {
    //                            // 计算点位1 (hv_Row[i], hv_Column[i]) 和 点位2 (hv_Row2[i], hv_Column2[i]) 之间的欧几里得距离
    //                            double distance = Math.Sqrt(Math.Pow(hv_Row[ii].D - hv_Row2[ii].D, 2) + Math.Pow(hv_Column[ii].D - hv_Column2[ii].D, 2));

    //                            // 判断是否为最小距离
    //                            if (distance < minDistance)
    //                            {
    //                                minDistance = distance;
    //                                minIndex = ii; // 更新最小距离的位置
    //                            }

    //                            // 判断是否为最大距离
    //                            if (distance > maxDistance)
    //                            {
    //                                maxDistance = distance;
    //                                maxIndex = ii; // 更新最大距离的位置
    //                            }
    //                        }
    //                        if (form.comboBox1.Text == "最小距离")
    //                        {
    //                            midRow1 = hv_Row[minIndex];
    //                            midCol1 = hv_Column[minIndex];
    //                        }
    //                        else if (form.comboBox1.Text == "最大距离")
    //                        {
    //                            midRow1 = hv_Row[maxIndex];
    //                            midCol1 = hv_Column[maxIndex];
    //                        }
    //                    }
    //                    if (form.comboBox2.Text=="左右排序")
    //                    {
    //                        // 8. 计算线段1的斜率
    //                        double deltaX1 = hv_Column[hv_Column.Length - 1].D - hv_Column[0].D;
    //                        double deltaY1 = hv_Row[hv_Row.Length - 1].D - hv_Row[0].D;

    //                        if (deltaX1 != 0)
    //                        {
    //                            double slope1 = deltaY1 / deltaX1;
    //                            double slopePerpendicular = -1 / slope1;

    //                            // 9. 生成垂直线
    //                            // 确保 x1 和 x2 在有效范围内
    //                            double x1 = Math.Max(Math.Min(midCol1 - 1000, 32767), -32768);
    //                            double x2 = Math.Max(Math.Min(midCol1 + 1000, 32767), -32768);

    //                            // 计算 y1 和 y2
    //                            double y1 = slopePerpendicular * (x1 - midCol1) + midRow1;
    //                            double y2 = slopePerpendicular * (x2 - midCol1) + midRow1;

    //                            // 确保 y1 和 y2 在有效范围内
    //                            y1 = Math.Max(Math.Min(y1, 32767), -32768);
    //                            y2 = Math.Max(Math.Min(y2, 32767), -32768);
    //                            HOperatorSet.GenRegionLine(out HObject perpendicularLine, y1, x1, y2, x2);
    //                            // 10. 计算垂线与线段2的交点
    //                            HTuple hv_IntersectionRow, hv_IntersectionCol, hv_IsParallel;
    //                            HOperatorSet.IntersectionLines(midRow1, midCol1, y2, x2, hv_Row2[0].D, hv_Column2[0].D, hv_Row2[hv_Row2.Length - 1].D, hv_Column2[hv_Column2.Length - 1].D, out hv_IntersectionRow, out hv_IntersectionCol, out hv_IsParallel);
    //                            if (hv_IsParallel == 0) // 如果没有平行，显示交点
    //                            {
    //                                //交点1
    //                                HOperatorSet.GenCrossContourXld(out HObject cross, hv_IntersectionRow, hv_IntersectionCol, double.Parse(form.pigBox.Text), new HTuple(45).TupleRad());
    //                                HOperatorSet.SetColor(hw.HalconWindow, "blue");
    //                                HOperatorSet.DispObj(cross, hw.HalconWindow);
    //                                HOperatorSet.SetColor(hw.HalconWindow, "green");
    //                                //交点2
    //                                HOperatorSet.GenCrossContourXld(out HObject cross2, midRow1, midCol1, double.Parse(form.pigBox.Text), new HTuple(45).TupleRad());
    //                                HOperatorSet.DispObj(cross2,hw.HalconWindow);

    //                                //显示线段 hv_IntersectionRow, hv_IntersectionCol, midRow1, midCol1
    //                                HOperatorSet.GenContourPolygonXld(out HObject linePoints, new double[] { hv_IntersectionRow, midRow1 }, new double[] { hv_IntersectionCol, midCol1 });
    //                                HOperatorSet.GenRegionLine(out HObject lineCenter, hv_IntersectionRow, hv_IntersectionCol, midRow1, midCol1);
    //                                HOperatorSet.DispObj(linePoints, hw.HalconWindow);
    //                                //处理结果数据
    //                                HOperatorSet.DistancePp(hv_IntersectionRow, hv_IntersectionCol, midRow1, midCol1, out HTuple distancesss);
    //                                HideOutputArrayDistances[i] = distancesss;
    //                                form.dataGridView1.Rows.Add(i, distancesss);
    //                                //将数据给间距数组
    //                                linesList[i, 0] = hv_Row[0];
    //                                linesList[i, 1] = hv_Column[0];
    //                                linesList[i, 2] = hv_Row2[0];
    //                                linesList[i, 3] = hv_Column2[0];
    //                                //显示文本
    //                                HOperatorSet.AreaCenter(lineCenter, out HTuple area3, out HTuple rowLine3, out HTuple columnLine3);
    //                                HideOutputArrayRows[i] = rowLine3;
    //                                HideOutputArrayColumns[i] = columnLine3;
    //                                //这段代码不要写到硬触发方法里面 点位选取功能
    //                                for (int indexi = 0; indexi < hv_Row.Length; indexi++)//线1的点位
    //                                {
    //                                    form.line1DataGridView.Rows.Add(indexi, hv_Row[indexi].D, hv_Column[indexi].D);
    //                                }
    //                                form.line2DataGridView.Rows.Clear();
    //                                for (int indexi = 0; indexi < hv_Row2.Length; indexi++)//线2的点位
    //                                {
    //                                    form.line2DataGridView.Rows.Add(indexi, hv_Row2[indexi].D, hv_Column2[indexi].D);
    //                                }

    //                            }
    //                            else
    //                            {
    //                                // 处理平行的情况
    //                                Console.WriteLine("线段1和线段2平行，无法计算交点");
    //                            }
    //                        }
    //                    }else if (form.comboBox2.Text == "上下排序")
    //                    {
    //                        // 1. 计算线段1的斜率
    //                        double deltaY1 = hv_Row[hv_Row.Length - 1].D - hv_Row[0].D;
    //                        double deltaX1 = hv_Column[hv_Column.Length - 1].D - hv_Column[0].D;

    //                        if (deltaY1 != 0)
    //                        {
    //                            double slope1 = deltaX1 / deltaY1; // 注意这里是deltaX1 / deltaY1
    //                            double slopePerpendicular = -1 / slope1;

    //                            // 2. 生成垂直线
    //                            // 确保 y1 和 y2 在有效范围内
    //                            double y1 = Math.Max(Math.Min(midRow1 - 1000, 32767), -32768);
    //                            double y2 = Math.Max(Math.Min(midRow1 + 1000, 32767), -32768);

    //                            // 计算 x1 和 x2
    //                            double x1 = slopePerpendicular * (y1 - midRow1) + midCol1;
    //                            double x2 = slopePerpendicular * (y2 - midRow1) + midCol1;

    //                            // 确保 x1 和 x2 在有效范围内
    //                            x1 = Math.Max(Math.Min(x1, 32767), -32768);
    //                            x2 = Math.Max(Math.Min(x2, 32767), -32768);

    //                            //HOperatorSet.GenRegionLine(out HObject perpendicularLine, y1, x1, y2, x2);

    //                            // 3. 计算垂线与线段2的交点
    //                            HTuple hv_IntersectionRow, hv_IntersectionCol, hv_IsParallel;
    //                            HOperatorSet.IntersectionLines(midRow1, midCol1, y2, x2,
    //                                hv_Row2[0].D, hv_Column2[0].D, hv_Row2[hv_Row2.Length - 1].D, hv_Column2[hv_Column2.Length - 1].D,
    //                                out hv_IntersectionRow, out hv_IntersectionCol, out hv_IsParallel);

    //                            if (hv_IsParallel == 0) // 如果没有平行，显示交点
    //                            {
    //                                //交点1
    //                                HOperatorSet.GenCrossContourXld(out HObject cross, hv_IntersectionRow, hv_IntersectionCol, 
    //                                    double.Parse(form.pigBox.Text), new HTuple(45).TupleRad());
    //                                HOperatorSet.SetColor(hw.HalconWindow, "blue");
    //                                HOperatorSet.DispObj(cross, hw.HalconWindow);
    //                                HOperatorSet.SetColor(hw.HalconWindow, "green");
    //                                //交点2
    //                                HOperatorSet.GenCrossContourXld(out HObject cross2, midRow1, midCol1, double.Parse(form.pigBox.Text), new HTuple(45).TupleRad());
    //                                HOperatorSet.DispObj(cross2, hw.HalconWindow);
    //                                // 显示线段和处理结果
    //                                HOperatorSet.GenContourPolygonXld(out HObject linePoints, new double[] { hv_IntersectionRow, midRow1 }, new double[] { hv_IntersectionCol, midCol1 });
    //                                HOperatorSet.GenRegionLine(out HObject lineCenter, hv_IntersectionRow, hv_IntersectionCol, midRow1, midCol1);
    //                                HOperatorSet.DispObj(linePoints, hw.HalconWindow);

    //                                // 处理距离数据
    //                                HOperatorSet.DistancePp(hv_IntersectionRow, hv_IntersectionCol, midRow1, midCol1, out HTuple distancesss);
    //                                HideOutputArrayDistances[i] = distancesss;
    //                                form.dataGridView1.Rows.Add(i, distancesss);
    //                                //将数据给间距数组
    //                                linesList[i, 0] = hv_Row[0];
    //                                linesList[i, 1] = hv_Column[0];
    //                                linesList[i, 2] = hv_Row2[0];
    //                                linesList[i, 3] = hv_Column2[0];
    //                                //显示文本
    //                                HOperatorSet.AreaCenter(lineCenter, out HTuple area3, out HTuple rowLine3, out HTuple columnLine3);
    //                                HideOutputArrayRows[i] = rowLine3;
    //                                HideOutputArrayColumns[i] = columnLine3;
    //                                //这段代码不要写到硬触发方法里面 点位选取功能
    //                                for (int indexi = 0; indexi < hv_Row.Length; indexi++)//线1的点位
    //                                {
    //                                    form.line1DataGridView.Rows.Add(indexi, hv_Row[indexi].D, hv_Column[indexi].D);
    //                                }
    //                                form.line2DataGridView.Rows.Clear();
    //                                for (int indexi = 0; indexi < hv_Row2.Length; indexi++)//线2的点位
    //                                {
    //                                    form.line2DataGridView.Rows.Add(indexi, hv_Row2[indexi].D, hv_Column2[indexi].D);
    //                                }
    //                            }
    //                            else
    //                            {
    //                                Console.WriteLine("线段1和线段2平行，无法计算交点");
    //                            }
    //                        }
    //                    }
                       
    //                }

    //            }
    //            catch (Exception ex)
    //            {
    //                throw new Exception("线段1抓取失败" + ex.Message);
    //            }
    //        }
        }
        /// <summary>
        /// 线与线中间放置卡尺
        /// </summary>
        public void Set_Line()
        {
            //if (HideIntputImage == null)
            //{
            //    throw new Exception("当前图像为空");
            //}
            //HWindow hv_WindowHandle = hw.HalconWindow;
            //hv_WindowHandle.ClearWindow();
            //hv_WindowHandle.DispObj(HideIntputImage);
            ////清除线段显示
            //if (line1Object != null && line2Object != null)
            //{
            //    line1Object.ClearDrawingObject();
            //    line2Object.ClearDrawingObject();
            //    //设置halcon图像模式
            //    HOperatorSet.SetSystem("clip_region", "false");
            //    var line1Params = new HTuple(double.Parse(form.caliper1Row1.Value + ""), double.Parse(form.caliper1Col1.Value + ""), double.Parse(form.caliper1Row2.Value + ""), double.Parse(form.caliper1Col2.Value + ""));
            //    //使用线段1的实例来找线
            //    HOperatorSet.CreateMetrologyModel(out HTuple hv_MetrologyHandle);
            //    HOperatorSet.AddMetrologyObjectGeneric(hv_MetrologyHandle, "line", line1Params, double.Parse(form.line1HeightBox.Value.ToString()), double.Parse(form.line1Width.Value.ToString()),
            //            double.Parse(form.line1muscle.Value.ToString()), double.Parse(form.line1contrast.Value.ToString()), new HTuple(), new HTuple(), out HTuple hv_Index);
            //    //该参数指定暗/亮或亮/暗边的使用  negative:正极性  positive:负极性  uniform:正负极性只有一个
            //    //获取极性
            //    string polarity = "";
            //    if (form.line1Combox.Text == "由明向暗")
            //    {
            //        polarity = "negative";
            //    }
            //    if (form.line1Combox.Text == "由暗向明")
            //    {
            //        polarity = "positive";
            //    }
            //    else
            //    {
            //        polarity = "all";
            //    }
            //    //设置极性
            //    HOperatorSet.SetMetrologyObjectParam(hv_MetrologyHandle, "all", "measure_transition", polarity);
            //    //卡尺的数量
            //    HOperatorSet.SetMetrologyObjectParam(hv_MetrologyHandle, "all", "num_measures", int.Parse(form.line1NumberBox.Value + ""));
            //    //卡尺卡的数量 接受的结果数
            //    HOperatorSet.SetMetrologyObjectParam(hv_MetrologyHandle, "all", "num_instances", 1);
            //    //bilinear
            //    HOperatorSet.SetMetrologyObjectParam(hv_MetrologyHandle, "all", "measure_interpolation", "bicubic");

            //    HOperatorSet.SetMetrologyObjectParam(hv_MetrologyHandle, "all", "measure_select", "all");
            //    //最小分数
            //    HOperatorSet.SetMetrologyObjectParam(hv_MetrologyHandle, "all", "min_score", double.Parse(form.line1small.Value.ToString()));

            //    //开始抓
            //    HOperatorSet.ApplyMetrologyModel(HideIntputImage, hv_MetrologyHandle);

            //    HOperatorSet.GetMetrologyObjectMeasures(out HObject ho_Contours, hv_MetrologyHandle, "all", "all",
            //        out HTuple hv_Row, out HTuple hv_Column);
            //    //gen_cross_contour_xld(Cross, Row1, Column1, 6, Phi)

            //    int index = 0;
            //    if (hv_Row.Length > 0 && hv_Column.Length > 0)
            //    {

            //        //得到距离在hv_Parameter中
            //        HOperatorSet.GetMetrologyObjectResult(hv_MetrologyHandle, 0, "all", "result_type", "all_param",
            //            out HTuple hv_Parameter);
            //        //没抓到
            //        if (hv_Parameter.Length > 0)
            //        {
            //            //设置边框颜色
            //            HOperatorSet.SetColor(hw.HalconWindow, "green");

            //            //显示边框区域
            //            HOperatorSet.DispObj(ho_Contours, hw.HalconWindow);

            //            HOperatorSet.GetMetrologyObjectResultContour(out HObject ho_Contour, hv_MetrologyHandle, 0, "all", 1.5);
            //            //中心线颜色
            //            HOperatorSet.SetColor(hw.HalconWindow, "green");

            //            HOperatorSet.SetLineWidth(hw.HalconWindow, 3);
            //            HOperatorSet.DispObj(ho_Contour, hw.HalconWindow);
            //            HOperatorSet.DistancePp(hv_Parameter[0], hv_Parameter
            //                [1], hv_Parameter[2], hv_Parameter[3], out HTuple distance);
            //            //添加结果集
            //            HOperatorSet.SetLineWidth(hw.HalconWindow, 1);
            //        }
            //    }

            //    //保存基准数据 1
            //    line1counterFrist = new List<double>();
            //    List<double> line1Doubles = new List<double>();
            //    //记录第一次模板的位置
            //    line1counterFrist.Add(HideIntputArrayRows[0]);
            //    line1counterFrist.Add(HideIntputArrayColumns[0]);
            //    line1counterFrist.Add(HideIntputArrayPhis[0]);
            //    //保存线段数据
            //    line1Doubles.Add(double.Parse(form.caliper1Row1.Value + ""));
            //    line1Doubles.Add(double.Parse(form.caliper1Col1.Value + ""));
            //    line1Doubles.Add(double.Parse(form.caliper1Row2.Value + ""));
            //    line1Doubles.Add(double.Parse(form.caliper1Col2.Value + ""));
            //    //将这个基准数据进行保存
            //    string path = $@"Data\工程文件\{hwindowFlowNode.projectName}\{hwindowFlowNode.name}任务文件\精准测量工具卡尺校验数据\{form.nodeName}\测量线1基准数据";
            //    if (Directory.Exists(path))
            //    {
            //        Directory.Delete(path, true);
            //    }
            //    Directory.CreateDirectory(path);
            //    HelpJsons.Write<double>(line1counterFrist, path + "\\线1线段模板基准数据.json");
            //    HelpJsons.Write<double>(line1Doubles, path + "\\线段1点位数据.json");


            //    line2counterFrist = new List<double>();
            //    List<double> line2Doubles = new List<double>();
            //    //记录第一次模板的位置
            //    line2counterFrist.Add(HideIntputArrayRows[0]);
            //    line2counterFrist.Add(HideIntputArrayColumns[0]);
            //    line2counterFrist.Add(HideIntputArrayPhis[0]);

            //    //保存线段数据 2
            //    line2Doubles.Add(double.Parse(form.caliper2Row1.Value + ""));
            //    line2Doubles.Add(double.Parse(form.caliper2Row1.Value + ""));
            //    line2Doubles.Add(double.Parse(form.caliper2Row1.Value + ""));
            //    line2Doubles.Add(double.Parse(form.caliper2Row1.Value + ""));
            //    //将这个基准数据进行保存
            //    path = $@"Data\工程文件\{hwindowFlowNode.projectName}\{hwindowFlowNode.name}任务文件\精准测量工具卡尺校验数据\{form.nodeName}\测量线2基准数据";
            //    if (Directory.Exists(path))
            //    {
            //        Directory.Delete(path, true);
            //    }
            //    Directory.CreateDirectory(path);
            //    HelpJsons.Write<double>(line2counterFrist, path + "\\线2线段模板基准数据.json");
            //    HelpJsons.Write<double>(line2Doubles, path + "\\线段2点位数据.json");


            //    //抓线段2
            //    line1Params = new HTuple(double.Parse(form.caliper2Row1.Value + ""), double.Parse(form.caliper2Col1.Value + ""), double.Parse(form.caliper2Row2.Value + ""), double.Parse(form.caliper2Col2.Value + ""));
            //    //使用线段1的实例来找线
            //    HOperatorSet.CreateMetrologyModel(out hv_MetrologyHandle);
            //    HOperatorSet.AddMetrologyObjectGeneric(hv_MetrologyHandle, "line", line1Params, double.Parse(form.line2HeightBox.Value.ToString()), double.Parse(form.line2Width.Value.ToString()),
            //            double.Parse(form.line2muscle.Value.ToString()), double.Parse(form.line2contrast.Value.ToString()), new HTuple(), new HTuple(), out hv_Index);
            //    //该参数指定暗/亮或亮/暗边的使用  negative:正极性  positive:负极性  uniform:正负极性只有一个
            //    //获取极性
            //    string polarity2 = "";//由明向暗
            //    if (form.line2Combox.Text == "由明向暗")
            //    {
            //        polarity2 = "negative";
            //    }
            //    if (form.line2Combox.Text == "由暗向明")
            //    {
            //        polarity2 = "positive";
            //    }
            //    else
            //    {
            //        polarity2 = "all";
            //    }
            //    //设置极性
            //    HOperatorSet.SetMetrologyObjectParam(hv_MetrologyHandle, "all", "measure_transition", polarity2);
            //    //卡尺的数量
            //    HOperatorSet.SetMetrologyObjectParam(hv_MetrologyHandle, "all", "num_measures", int.Parse(form.line2NumberBox.Value + ""));
            //    //卡尺卡的数量 接受的结果数
            //    HOperatorSet.SetMetrologyObjectParam(hv_MetrologyHandle, "all", "num_instances", 1);
            //    //bilinear
            //    HOperatorSet.SetMetrologyObjectParam(hv_MetrologyHandle, "all", "measure_interpolation", "bicubic");

            //    HOperatorSet.SetMetrologyObjectParam(hv_MetrologyHandle, "all", "measure_select", "all");
            //    //最小分数
            //    HOperatorSet.SetMetrologyObjectParam(hv_MetrologyHandle, "all", "min_score", double.Parse(form.line2small.Value.ToString()));

            //    //开始抓
            //    HOperatorSet.ApplyMetrologyModel(HideIntputImage, hv_MetrologyHandle);

            //    HOperatorSet.GetMetrologyObjectMeasures(out ho_Contours, hv_MetrologyHandle, "all", "all",
            //        out hv_Row, out hv_Column);
            //    //显示点
            //    if (hv_Row.Length > 0 && hv_Column.Length > 0)
            //    {

            //        //得到距离在hv_Parameter中
            //        HOperatorSet.GetMetrologyObjectResult(hv_MetrologyHandle, 0, "all", "result_type", "all_param",
            //            out HTuple hv_Parameter);
            //        //没抓到
            //        if (hv_Parameter.Length > 0)
            //        {
            //            //设置边框颜色
            //            HOperatorSet.SetColor(hw.HalconWindow, "green");

            //            //显示边框区域
            //            HOperatorSet.DispObj(ho_Contours, hw.HalconWindow);

            //            HOperatorSet.GetMetrologyObjectResultContour(out HObject ho_Contour, hv_MetrologyHandle, 0, "all", 1.5);
            //            //中心线颜色
            //            HOperatorSet.SetColor(hw.HalconWindow, "green");

            //            HOperatorSet.SetLineWidth(hw.HalconWindow, 3);
            //            HOperatorSet.DispObj(ho_Contour, hw.HalconWindow);
            //            HOperatorSet.DistancePp(hv_Parameter[0], hv_Parameter
            //                [1], hv_Parameter[2], hv_Parameter[3], out HTuple distance);
            //            HOperatorSet.SetLineWidth(hw.HalconWindow, 1);
            //        }
            //    }
            //}
        }
        /// <summary>
        /// 矩形找点功能
        /// </summary>
        public HDrawingObject regionPoint1;//矩形1对象
        public HDrawingObject regionPoint2;//矩形2对象
        public List<double> pmaListDouble = new List<double>();//模板的基准位置
        /// <summary>
        /// 生成2个矩形
        /// </summary>
        public void DrawPonint1Point2()
        {
            try
            {
                hw.HalconWindow.ClearWindow();
                hw.HalconWindow.DispObj(HideIntputImage);
                HOperatorSet.SetDraw(hwindowFlowNode.hSmartWindowControl1.HalconWindow, "fill");
                HOperatorSet.SetColor(hwindowFlowNode.hSmartWindowControl1.HalconWindow, "blue");
                //生成一个参照点
                HOperatorSet.GenCircle(out HObject circle1, HideIntputArrayRows[0], HideIntputArrayColumns[0], 10);
                HOperatorSet.DispObj(circle1, hw.HalconWindow);
                HOperatorSet.SetDraw(hwindowFlowNode.hSmartWindowControl1.HalconWindow, "margin");
                HOperatorSet.SetColor(hwindowFlowNode.hSmartWindowControl1.HalconWindow,"green");
                //矩形1
                //定义绘制线的开始坐标与结束坐标 
                //从界面读取数据进行生成
                double line1_row = double.Parse(form.re1numberRow.Value.ToString());
                double line1_col = double.Parse(form.re1numberColumn.Value.ToString());
                double line1_angle = double.Parse(form.reg1Angle.Value.ToString());
                double line1_length1 = double.Parse(form.reg1Width.Value.ToString());
                double line1_length2 = double.Parse(form.reg1Hegiht.Value.ToString());
                var lineTuple1 = new HTuple[] { line1_row, line1_col, line1_angle, line1_length2, line1_length1 };
                //创建矩形的对象
                regionPoint1 = HDrawingObject.CreateDrawingObject(HDrawingObject.HDrawingObjectType.RECTANGLE2, lineTuple1);
                regionPoint1.SetDrawingObjectParams("color", "blue");
                //矩形拖动触发事件注册
                regionPoint1.OnDrag(LineOnDragPoint1);
                //线段长度修改触发事件注册
                regionPoint1.OnResize(LineOnResizePoint1);
                //矩形2
                //从界面读取数据进行生成
                double line2_row = double.Parse(form.re2numberRow.Value.ToString());
                double line2_col = double.Parse(form.re2numberColumn.Value.ToString());
                double line2_angle = double.Parse(form.reg2Angle.Value.ToString());
                double line2_length1 = double.Parse(form.reg2Width.Value.ToString());
                double line2_length2 = double.Parse(form.reg2Hegiht.Value.ToString());
                //定义绘制线的开始坐标与结束坐标
                var lineTuple2 = new HTuple[] { line2_row, line2_col, line2_angle, line2_length2, line2_length1 };
                //创建矩形的对象
                regionPoint2 = HDrawingObject.CreateDrawingObject(HDrawingObject.HDrawingObjectType.RECTANGLE2, lineTuple2);
                regionPoint2.SetDrawingObjectParams("color", "green");
                //矩形拖动触发事件注册
                regionPoint2.OnDrag(LineOnDragPoints2);
                //线段长度修改触发事件注册
                regionPoint2.OnResize(LineOnResizePoints2);
                pmaListDouble = new List<double>();
                WriteRegoinList();
                //增加这个对象到指定Halcon窗口
                hw.HalconWindow.AttachDrawingObjectToWindow(regionPoint1);
                hw.HalconWindow.AttachDrawingObjectToWindow(regionPoint2);
            }
            catch { }
        }
        /// <summary>
        /// 矩形1拖动事件
        /// </summary>
        /// <param name="drawid"></param>
        /// <param name="window"></param>
        /// <param name="type"></param>
        private void LineOnResizePoint1(HDrawingObject drawid, HWindow window, string type)
        {
            UpdataDrawingPoint1(drawid);
        }

        private void LineOnDragPoint1(HDrawingObject drawid, HWindow window, string type)
        {
            UpdataDrawingPoint1(drawid);
        }
        //矩形框1的方向朝向
        public string recDirection1 = "";
        public void UpdataDrawingPoint1(HDrawingObject drawid)
        {
            try
            {
                (FormDb.Db["Form1"] as Form1).Cursor = Cursors.Cross;
                //创建一个要得到对象属性的元组
                var attTuple = new HTuple("row", "column", "phi", "length1", "length2");
                //获取对应的属性
                var valueTuple = drawid.GetDrawingObjectParams(attTuple);
                //将位置给界面数据
                form.re1numberRow.Value = decimal.Parse(valueTuple[0].D.ToString());
                form.re1numberColumn.Value = decimal.Parse(valueTuple[1].D.ToString());
                form.reg1Angle.Value = decimal.Parse(valueTuple[2].D.ToString());
                form.reg1Hegiht.Value = decimal.Parse(valueTuple[3].D.ToString());
                form.reg1Width.Value = decimal.Parse(valueTuple[4].D.ToString());
                
                ////实时抓取点信息
                try
                {
                    double anglePoint1 = new HTuple(valueTuple[2].D).TupleDeg();
                    if ((anglePoint1 >= 315 && anglePoint1 < 360) || (anglePoint1 >= 0 && anglePoint1 < 45))  // 右
                    {
                        // 右
                        recDirection1 = "由左向右";
                    }
                    else if (anglePoint1 >= 45 && anglePoint1 < 135)  // 上
                    {
                        // 上
                        recDirection1 = "由下向上";
                    }
                    else if (anglePoint1 >= 135 && anglePoint1 < 225)  // 左
                    {
                        // 左
                        recDirection1 = "由右向左";
                    }
                    else if (anglePoint1 >= 225 && anglePoint1 < 315)  // 下
                    {
                        // 下
                        recDirection1 = "由上向下";
                    }
                }
                catch { }
                //记录基准数据
                WriteRegoinList("矩形1", recDirection1);
            }
            catch { }
        }
        /// <summary>
        /// 矩形2拖动事件
        /// </summary>
        /// <param name="drawid"></param>
        /// <param name="window"></param>
        /// <param name="type"></param>
        private void LineOnResizePoints2(HDrawingObject drawid, HWindow window, string type)
        {
            UpdataDrawingPoints2(drawid);
        }
        private void LineOnDragPoints2(HDrawingObject drawid, HWindow window, string type)
        {
            UpdataDrawingPoints2(drawid);
        }
        //矩形框2的方向朝向
        public string recDirection2 = "";
        public void UpdataDrawingPoints2(HDrawingObject drawid)
        {
            try
            {
                (FormDb.Db["Form1"] as Form1).Cursor = Cursors.Cross;
                //Application.DoEvents();
                //创建一个要得到对象属性的元组
                var attTuple = new HTuple("row", "column", "phi", "length1", "length2");
                //获取对应的属性
                var valueTuple = drawid.GetDrawingObjectParams(attTuple);
                //将位置给界面数据
                form.re2numberRow.Value = decimal.Parse(valueTuple[0].D.ToString());
                form.re2numberColumn.Value = decimal.Parse(valueTuple[1].D.ToString());
                form.reg2Angle.Value = decimal.Parse(valueTuple[2].D.ToString());
                form.reg2Hegiht.Value = decimal.Parse(valueTuple[3].D.ToString());
                form.reg2Width.Value = decimal.Parse(valueTuple[4].D.ToString());
                try
                {
                    double anglePoint2 = new HTuple(valueTuple[2].D).TupleDeg();
                    if ((anglePoint2 >= 315 && anglePoint2 < 360) || (anglePoint2 >= 0 && anglePoint2 < 45))  // 右
                    {
                        // 右
                        recDirection2 = "由左向右";
                    }
                    else if (anglePoint2 >= 45 && anglePoint2 < 135)  // 上
                    {
                        // 上
                        recDirection2 = "由下向上";
                    }
                    else if (anglePoint2 >= 135 && anglePoint2 < 225)  // 左
                    {
                        // 左
                        recDirection2 = "由右向左";
                    }
                    else if (anglePoint2 >= 225 && anglePoint2 < 315)  // 下
                    {
                        // 下
                        recDirection2 = "由上向下";
                    }
                }
                catch { }
                WriteRegoinList("矩形2", recDirection2);
            }
            catch { }
        }
        /// <summary>
        /// 点位矩形放置功能
        /// </summary>
        public void Set_Point()
        {
            HWindow hv_WindowHandle = hw.HalconWindow;
            hv_WindowHandle.ClearWindow();
            hv_WindowHandle.DispObj(HideIntputImage);
            WriteRegoinList();
            //生成矩形框1
            HOperatorSet.GenRectangle2(out HObject rectangle1, double.Parse(form.re1numberRow.Value.ToString()), double.Parse(form.re1numberColumn.Value.ToString()), double.Parse(form.reg1Angle.Value.ToString()), double.Parse(form.reg1Hegiht.Value.ToString()), double.Parse(form.reg1Width.Value.ToString()));



            ////实时抓取点信息
            try
            {
                double anglePoint1 = new HTuple(double.Parse(form.reg1Angle.Value + "")).TupleDeg();
                if ((anglePoint1 >= 315 && anglePoint1 < 360) || (anglePoint1 >= 0 && anglePoint1 < 45))  // 右
                {
                    // 右
                    recDirection1 = "由左向右";
                }
                else if (anglePoint1 >= 45 && anglePoint1 < 135)  // 上
                {
                    // 上
                    recDirection1 = "由下向上";
                }
                else if (anglePoint1 >= 135 && anglePoint1 < 225)  // 左
                {
                    // 左
                    recDirection1 = "由右向左";
                }
                else if (anglePoint1 >= 225 && anglePoint1 < 315)  // 下
                {
                    // 下
                    recDirection1 = "由上向下";
                }
            }
            catch { }
            //记录基准数据
            WriteRegoinList("矩形1", recDirection1);


            //生成矩形框2
            HOperatorSet.GenRectangle2(out HObject rectangle2, double.Parse(form.re2numberRow.Value.ToString()), double.Parse(form.re2numberColumn.Value.ToString()), double.Parse(form.reg2Angle.Value.ToString()), double.Parse(form.reg2Hegiht.Value.ToString()), double.Parse(form.reg2Width.Value.ToString()));
            HOperatorSet.SetColor(hw.HalconWindow, "blue");
            HOperatorSet.DispObj(rectangle1, hw.HalconWindow);
            HOperatorSet.SetColor(hw.HalconWindow, "green");
            HOperatorSet.DispObj(rectangle2, hw.HalconWindow);

            //将位置给界面数据
            try
            {
                double anglePoint2 = new HTuple(double.Parse(form.reg2Angle.Value+"")).TupleDeg();
                if ((anglePoint2 >= 315 && anglePoint2 < 360) || (anglePoint2 >= 0 && anglePoint2 < 45))  // 右
                {
                    // 右
                    recDirection2 = "由左向右";
                }
                else if (anglePoint2 >= 45 && anglePoint2 < 135)  // 上
                {
                    // 上
                    recDirection2 = "由下向上";
                }
                else if (anglePoint2 >= 135 && anglePoint2 < 225)  // 左
                {
                    // 左
                    recDirection2 = "由右向左";
                }
                else if (anglePoint2 >= 225 && anglePoint2 < 315)  // 下
                {
                    // 下
                    recDirection2 = "由上向下";
                }
            }
            catch { }
            WriteRegoinList("矩形2", recDirection2);


            //清除计量模型
            if (regionPoint1 != null)
            {
                regionPoint1.ClearDrawingObject();
            }
            if (regionPoint2 != null)
            {
                regionPoint2.ClearDrawingObject();
            }
        }

        /// <summary>
        /// 写入点功能模板基准数据
        /// </summary>
        /// <param name="recName">矩形序号</param>
        public void WriteRegoinList(string recName="",string recData="")
        {
            try
            {
                //记录基准数据
                pmaListDouble.Clear();
                pmaListDouble.Add(HideIntputArrayRows[0]);
                pmaListDouble.Add(HideIntputArrayColumns[0]);
                pmaListDouble.Add(HideIntputArrayPhis[0]);
                string path = $@"Data\工程文件\{hwindowFlowNode.projectName}\{hwindowFlowNode.name}任务文件\精准测量工具卡尺校验数据\{form.nodeName}\点功能基准数据";
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }
                HelpJsons.Write<double>(pmaListDouble, path + "\\点功能模板基准数据.json");
                if (recName!=""&&recData!="")
                {
                    List<string> list = new List<string>(); 
                    list.Add(recData);
                    HelpJsons.Write<string>(list, path + $"\\{recName}朝向数据.json");
                }
                
            }
            catch { }
        }
        /// <summary>
        /// 找点功能运行功能
        /// </summary>
        private void Point1Point2Run()
        {
            HOperatorSet.SetDraw(hw.HalconWindow, "margin");
            if (pmaListDouble.Count == 0)
            {
                pmaListDouble = HelpJsons.Read<double>(path + "\\" + "点功能基准数据" + "\\点功能模板基准数据.json");
            }
            if (recDirection1 == "")
            {
                List<string> point1List = new List<string>();
                point1List = HelpJsons.Read<string>(path + "\\" + "点功能基准数据" + "\\矩形1朝向数据.json");
                if (point1List.Count > 0)
                {
                    recDirection1 = point1List[0];
                }
            }
            if (recDirection2 == "")
            {
                List<string> point2List = new List<string>();
                point2List = HelpJsons.Read<string>(path + "\\" + "点功能基准数据" + "\\矩形2朝向数据.json");
                if (point2List.Count > 0)
                {
                    recDirection2 = point2List[0];
                }
            }
            HideOutputArrayRows = new double[HideIntputArrayColumns.Length];
            HideOutputArrayColumns = new double[HideIntputArrayColumns.Length];
            HideOutputArrayDistances = new double[HideIntputArrayColumns.Length];
            linesList = new double[HideIntputArrayColumns.Length, 4];
            form.line1DataGridView.Rows.Clear();
            form.line2DataGridView.Rows.Clear();
            form.dataGridView1.Rows.Clear();
            //卡尺宽度
            double caliper_width1 = double.Parse(form.caliper_1_width.Value + "");
            double caliper_width2 = double.Parse(form.caliper_2_width.Value + "");
            //平滑系数

            //平滑系数
            double sigam1 = double.Parse(form.smoothReg1.Value + "");
            double sigam2 = double.Parse(form.smoothReg2.Value + "");
            //对比度系数
            double threshod1 = double.Parse(form.thresholdMinReg1.Value + "");
            double threshod2 = double.Parse(form.thresholdMinReg2.Value + "");
            //搜索结果 'first','last','all'
            string select = "first";
            //极性  由明向暗  由暗向明
            string polarity_region1 = form.region_1_direction.Text + ""; //矩形1方向
            string polarity_region2 = form.region_2_direction.Text + "";  //矩形2方向

            //recDirection1      //recDirection2

            //卡尺数量
            int caliperNum1 = int.Parse(form.numberReg1.Value + "");
            int caliperNum2 = int.Parse(form.numberReg2.Value + "");

            //选择的测量极性方向******************************** 矩形1
            if (polarity_region1 == "由明向暗")
            {
                polarity_region1 = "negative";
            }
            else if (polarity_region1 == "由暗向明")
            {
                polarity_region1 = "positive";
            }
            else
            {
                polarity_region1 = "all";
            }

            //选择的测量极性方向******************************** 矩形2
            if (polarity_region2 == "由明向暗")
            {
                polarity_region2 = "negative";
            }
            else if (polarity_region2 == "由暗向明")
            {
                polarity_region2 = "positive";
            }
            else
            {
                polarity_region2 = "all";
            }

            //*计算直线角度定义变量
            //获取图片大小
            HOperatorSet.GetImageSize(HideIntputImage, out HTuple width, out HTuple height);

            //获取到矩形框1的信息2个矩形框
            for (int i = 0; i < HideIntputArrayColumns.Length; i++)
            {
                //生成矩形框1
                HOperatorSet.GenRectangle2(out HObject rectangle1, double.Parse(form.re1numberRow.Value.ToString()), double.Parse(form.re1numberColumn.Value.ToString()), double.Parse(form.reg1Angle.Value.ToString()), double.Parse(form.reg1Hegiht.Value.ToString()), double.Parse(form.reg1Width.Value.ToString()));
                //生成矩形框2
                HOperatorSet.GenRectangle2(out HObject rectangle2, double.Parse(form.re2numberRow.Value.ToString()), double.Parse(form.re2numberColumn.Value.ToString()), double.Parse(form.reg2Angle.Value.ToString()), double.Parse(form.reg2Hegiht.Value.ToString()), double.Parse(form.reg2Width.Value.ToString()));

                //生成第一个跟随的矩形
                HObject ho_RegionAffineTrans1 = UtiyHalcon.MatrixCalculate(rectangle1, HideIntputArrayRows[i], HideIntputArrayColumns[i], HideIntputArrayPhis[i], pmaListDouble[0], pmaListDouble[1], pmaListDouble[2]);

                //生成第二个跟随的矩形
                HObject ho_RegionAffineTrans2 = UtiyHalcon.MatrixCalculate(rectangle2, HideIntputArrayRows[i], HideIntputArrayColumns[i], HideIntputArrayPhis[i], pmaListDouble[0], pmaListDouble[1], pmaListDouble[2]);


                //第一个矩形
                HOperatorSet.GetRegionContour(ho_RegionAffineTrans1, out HTuple rows, out HTuple columns);
                //矩形左上角
                HOperatorSet.TupleMin(rows, out HTuple LeftTop_Row);
                HOperatorSet.TupleMin(columns, out HTuple LeftTop_Col);
                //矩形右下角
                HOperatorSet.TupleMax(rows, out HTuple RigthButoon_Row);
                HOperatorSet.TupleMax(columns, out HTuple RigthButoon_Columns);
                //******   计算直线角度，根据直线角度及测量方向测算测量矩形的方向phi
                double L1Measure = 0;  //宽度
                double MeasureR1 = 0;  //行
                double MeasureC1 = 0;  //列
                double offestOfRow = 0; //偏移行
                double offestOfCol = 0; //偏移列
                double Phi = 0; //角度
                //开始计算
                Calculate_Office(recDirection1, LeftTop_Row, LeftTop_Col, RigthButoon_Row, RigthButoon_Columns, caliper_width1, caliperNum1, out L1Measure, out MeasureR1, out MeasureC1, out offestOfRow, out offestOfCol, out Phi);

                //点位2的数据集合
                List<double> rowPoint1 = new List<double>();
                List<double> colPoint1 = new List<double>();

                //创建测量模型
                HOperatorSet.GenMeasureRectangle2(MeasureR1, MeasureR1, Phi, L1Measure, caliper_width1, width, height, "nearest_neighbor", out HTuple MeasureHandle);
                //矩形1的找点
                for (int j = 1; j < caliperNum1 + 1; j++)
                {
                    try
                    {
                        HOperatorSet.TranslateMeasure(MeasureHandle, MeasureR1 + offestOfRow * (j - 1), MeasureC1 + offestOfCol * (j - 1));
                        HOperatorSet.GenRectangle2(out HObject hObject, MeasureR1 + offestOfRow * (j - 1), MeasureC1 + offestOfCol * (j - 1), Phi, L1Measure, caliper_width1);
                        if (form.comboBox4.Text == "开启")
                        {
                            HOperatorSet.DispObj(hObject, hw.HalconWindow);
                        }
                        //measure_pos(Image, MeasureHandle, Sigam, Threshod, polarity, Select, RowEdge, ColumnEdge, Amplitude, Distance)
                        HOperatorSet.MeasurePos(HideIntputImage, MeasureHandle, sigam1, threshod1, polarity_region1, select, out HTuple RowEdge, out HTuple ColumnEdge, out HTuple Amplitude, out HTuple Distance);
                        //判断是否在区域内
                        HOperatorSet.TestRegionPoint(ho_RegionAffineTrans1, RowEdge, ColumnEdge, out HTuple IsCheck);
                        if (IsCheck.D == 1)
                        {
                            //将数据给到集合中
                            rowPoint1.Add(RowEdge.D);
                            colPoint1.Add(ColumnEdge.D);
                            HOperatorSet.GenCrossContourXld(out HObject cross, RowEdge, ColumnEdge, double.Parse(form.pigBox.Text), new HTuple(45).TupleRad());
                            HOperatorSet.SetColor(hw.HalconWindow, "blue");
                            HOperatorSet.DispObj(cross, hw.HalconWindow);
                            HOperatorSet.SetColor(hw.HalconWindow, "green");
                        }
                    }
                    catch
                    {
                        continue;
                    }
                }
                //第二个矩形
                HOperatorSet.GetRegionContour(ho_RegionAffineTrans2, out rows, out columns);
                //矩形左上角
                HOperatorSet.TupleMin(rows, out LeftTop_Row);
                HOperatorSet.TupleMin(columns, out LeftTop_Col);
                //矩形右下角
                HOperatorSet.TupleMax(rows, out RigthButoon_Row);
                HOperatorSet.TupleMax(columns, out RigthButoon_Columns);

                //开始计算 
                Calculate_Office(recDirection2, LeftTop_Row, LeftTop_Col, RigthButoon_Row, RigthButoon_Columns, caliper_width2, caliperNum2, out L1Measure, out MeasureR1, out MeasureC1, out offestOfRow, out offestOfCol, out Phi);

                //创建测量模型
                HOperatorSet.GenMeasureRectangle2(MeasureR1, MeasureR1, Phi, L1Measure, caliper_width2, width, height, "nearest_neighbor", out MeasureHandle);

                //点位2的数据集合
                List<double> rowPoint2 = new List<double>();
                List<double> colPoint2 = new List<double>();

                //矩形2的找点//矩形2的找点
                for (int j = 1; j < caliperNum2 + 1; j++)
                {
                    try
                    {
                        HOperatorSet.TranslateMeasure(MeasureHandle, MeasureR1 + offestOfRow * (j - 1), MeasureC1 + offestOfCol * (j - 1));
                        HOperatorSet.GenRectangle2(out HObject hObject, MeasureR1 + offestOfRow * (j - 1), MeasureC1 + offestOfCol * (j - 1), Phi, L1Measure, caliper_width2);
                        if (form.comboBox4.Text == "开启")
                        {
                            HOperatorSet.DispObj(hObject, hw.HalconWindow);
                        }

                        HOperatorSet.MeasurePos(HideIntputImage, MeasureHandle, sigam2, threshod2, polarity_region2, select, out HTuple RowEdge, out HTuple ColumnEdge, out HTuple Amplitude, out HTuple Distance);
                        //判断是否在区域内
                        HOperatorSet.TestRegionPoint(ho_RegionAffineTrans2, RowEdge, ColumnEdge, out HTuple IsCheck);
                        if (IsCheck.D == 1)
                        {
                            //将数据给到集合中
                            rowPoint2.Add(RowEdge.D);
                            colPoint2.Add(ColumnEdge.D);
                            HOperatorSet.GenCrossContourXld(out HObject cross, RowEdge, ColumnEdge, double.Parse(form.pigBox.Text), new HTuple(45).TupleRad());
                            HOperatorSet.DispObj(cross, hw.HalconWindow);
                        }
                    }
                    catch
                    {
                        continue;
                    }
                }
                for (int ii = 0; ii < rowPoint1.Count; ii++)
                {
                    //将点位数据给界面
                    form.line1DataGridView.Rows.Add(ii, rowPoint1[ii], colPoint1[ii]);
                }
                for (int ii = 0; ii < rowPoint2.Count; ii++)
                {
                    //将点位数据给界面
                    form.line2DataGridView.Rows.Add(ii, rowPoint2[ii], colPoint2[ii]);
                }

                if (rowPoint1.Count > 0 && colPoint1.Count > 0 && rowPoint2.Count > 0 && colPoint2.Count > 0) // 找到点了
                {
                    // 假设 point1 和 point2 是已知的坐标
                    double point1_Row = 0, point1_Col = 0;
                    double point2_Row = 0, point2_Col = 0;

                    // 获取模板角度
                    double base_phi = pmaListDouble[2]; // 使用基准角度来生成线
                    double template_phi = HideIntputArrayPhis[i]; // 使用模板角度来生成线

                    // 计算最小距离、最大距离和中间距离
                    if (form.comboBox2.Text == "上下排序")
                    {
                        double point1Paper = rowPoint1.Max();
                        double point2Paper = rowPoint2.Min();
                        // 选择点的计算方式
                        if (form.comboBox1.Text == "最小距离")
                        {
                            if (point1Paper < point2Paper)
                            {
                                //计算点1行最大，点2最小就是最小距离
                                point1_Row = rowPoint1.Max();
                                int row1Index = rowPoint1.IndexOf(point1_Row);//下标
                                point1_Col = colPoint1[row1Index];
                                point2_Row = rowPoint2.Min();
                                int row2Index = rowPoint2.IndexOf(point2_Row);//下标
                                point2_Col = colPoint2[row2Index];
                            }
                            else
                            {
                                //计算点1行最大，点2最小就是最小距离
                                point1_Row = rowPoint1.Min();
                                int row1Index = rowPoint1.IndexOf(point1_Row);//下标
                                point1_Col = colPoint1[row1Index];
                                point2_Row = rowPoint2.Max();
                                int row2Index = rowPoint2.IndexOf(point2_Row);//下标
                                point2_Col = colPoint2[row2Index];
                            }
                        }
                        else if (form.comboBox1.Text == "中间距离")
                        {
                            point1_Row = rowPoint1[rowPoint1.Count / 2];
                            point1_Col = colPoint1[colPoint1.Count / 2];
                            point2_Row = rowPoint2[rowPoint2.Count / 2];
                            point2_Col = colPoint2[colPoint2.Count / 2];
                        }
                        else if (form.comboBox1.Text == "最大距离")
                        {
                            if (point1Paper < point2Paper)
                            {
                                //计算点1行最大，点2最小就是最小距离
                                point1_Row = rowPoint1.Min();
                                int row1Index = rowPoint1.IndexOf(point1_Row);//下标
                                point1_Col = colPoint1[row1Index];
                                point2_Row = rowPoint2.Max();
                                int row2Index = rowPoint2.IndexOf(point2_Row);//下标
                                point2_Col = colPoint2[row2Index];
                            }
                            else
                            {
                                //计算点1行最大，点2最小就是最小距离
                                point1_Row = rowPoint1.Max();
                                int row1Index = rowPoint1.IndexOf(point1_Row);//下标
                                point1_Col = colPoint1[row1Index];
                                point2_Row = rowPoint2.Min();
                                int row2Index = rowPoint2.IndexOf(point2_Row);//下标
                                point2_Col = colPoint2[row2Index];
                            }
                        }
                    }
                    else if (form.comboBox2.Text == "左右排序")//计算行坐标
                    {
                        double point1Paper = colPoint1.Max();
                        double point2Paper = colPoint2.Min();
                        // 选择点的计算方式
                        if (form.comboBox1.Text == "最小距离")
                        {
                            if (point1Paper < point2Paper)
                            {
                                //计算点1行最大，点2最小就是最小距离
                                point1_Col = colPoint1.Max();
                                int col1Index = colPoint1.IndexOf(point1_Col);//下标
                                point1_Row = rowPoint1[col1Index];
                                point2_Col = colPoint2.Min();
                                int col2Index = colPoint2.IndexOf(point2_Col);//下标
                                point2_Row = rowPoint2[col2Index];
                            }
                            else
                            {
                                //计算点1行最大，点2最小就是最小距离
                                point1_Col = colPoint1.Min();
                                int col1Index = colPoint1.IndexOf(point1_Col);//下标
                                point1_Row = rowPoint1[col1Index];
                                point2_Col = colPoint2.Max();
                                int col2Index = colPoint2.IndexOf(point2_Col);//下标
                                point2_Row = rowPoint2[col2Index];
                            }
                        }
                        else if (form.comboBox1.Text == "中间距离")
                        {
                            point1_Row = rowPoint1[rowPoint1.Count / 2];
                            point1_Col = colPoint1[colPoint1.Count / 2];
                            point2_Row = rowPoint2[rowPoint2.Count / 2];
                            point2_Col = colPoint2[colPoint2.Count / 2];
                        }
                        else if (form.comboBox1.Text == "最大距离")
                        {
                            if (point1Paper < point2Paper)
                            {
                                //计算点1行最大，点2最小就是最小距离
                                point1_Col = colPoint1.Min();
                                int col1Index = colPoint1.IndexOf(point1_Col);//下标
                                point1_Row = rowPoint1[col1Index];
                                point2_Col = colPoint2.Max();
                                int col2Index = colPoint2.IndexOf(point2_Col);//下标
                                point2_Row = rowPoint2[col2Index];
                            }
                            else
                            {
                                //计算点1行最大，点2最小就是最小距离
                                point1_Col = colPoint1.Max();
                                int col1Index = colPoint1.IndexOf(point1_Col);//下标
                                point1_Row = rowPoint1[col1Index];
                                point2_Col = colPoint2.Min();
                                int col2Index = colPoint2.IndexOf(point2_Col);//下标
                                point2_Row = rowPoint2[col2Index];
                            }

                        }
                    }

                    // 点1沿上下方向生成线
                    double deltaRow = point2_Row - point1_Row;
                    double line1_Start_Row = point1_Row;
                    double line1_Start_Col = point1_Col;
                    double line1_End_Row = point1_Row + Math.Sign(deltaRow) * 100;
                    double line1_End_Col = point1_Col;

                    // 使用模板角度进行旋转生成点2的线段
                    double line2_Start_Row = point2_Row;
                    double line2_Start_Col = point2_Col;
                    double line2_End_Row = point2_Row;
                    double line2_End_Col = point2_Col + Math.Sign(deltaRow) * 100 * Math.Cos(template_phi); // 使用模板角度


                    // 仿射变换当前线段1
                    HOperatorSet.HomMat2dIdentity(out HTuple homMat2DIdentity1);
                    HOperatorSet.HomMat2dRotate(homMat2DIdentity1, HideIntputArrayPhis[i] - pmaListDouble[2], line1_Start_Row, line1_Start_Col, out HTuple homMat2DRotate1);

                    // 延长线段1，首先计算延长的方向
                    double deltaRow1 = line1_End_Row - line1_Start_Row;
                    double deltaCol1 = line1_End_Col - line1_Start_Col;
                    double length1 = Math.Sqrt(deltaRow1 * deltaRow1 + deltaCol1 * deltaCol1);

                    // 延长线段1的起点和终点
                    double extensionFactor1 = 20; // 延长因子，1.5表示延长50%
                    double extendedStartRow1 = line1_Start_Row - extensionFactor1 * deltaRow1;
                    double extendedStartCol1 = line1_Start_Col - extensionFactor1 * deltaCol1;
                    double extendedEndRow1 = line1_End_Row + extensionFactor1 * deltaRow1;
                    double extendedEndCol1 = line1_End_Col + extensionFactor1 * deltaCol1;

                    // 显示延长后的线段1
                    HOperatorSet.GenRegionLine(out HObject regionLines1, extendedStartRow1, extendedStartCol1, extendedEndRow1, extendedEndCol1);
                    HOperatorSet.AffineTransRegion(regionLines1, out HObject regionAffineTrans1, homMat2DRotate1, "nearest_neighbor");
                    // HOperatorSet.DispObj(regionAffineTrans1, hw.HalconWindow);
                    HOperatorSet.GetRegionPoints(regionAffineTrans1, out HTuple rows1Points, out HTuple columns1Points);

                    // 仿射变换当前线段2
                    HOperatorSet.HomMat2dIdentity(out HTuple homMat2DIdentity2);
                    HOperatorSet.HomMat2dRotate(homMat2DIdentity2, HideIntputArrayPhis[i] - pmaListDouble[2], line2_Start_Row, line2_Start_Col, out HTuple homMat2DRotate2);

                    // 延长线段2，首先计算延长的方向
                    double deltaRow2 = line2_End_Row - line2_Start_Row;
                    double deltaCol2 = line2_End_Col - line2_Start_Col;
                    double length2 = Math.Sqrt(deltaRow2 * deltaRow2 + deltaCol2 * deltaCol2);

                    // 延长线段2的起点和终点
                    double extensionFactor2 = 20; // 延长因子，1.5表示延长50%
                    double extendedStartRow2 = line2_Start_Row - extensionFactor2 * deltaRow2;
                    double extendedStartCol2 = line2_Start_Col - extensionFactor2 * deltaCol2;
                    double extendedEndRow2 = line2_End_Row + extensionFactor2 * deltaRow2;
                    double extendedEndCol2 = line2_End_Col + extensionFactor2 * deltaCol2;

                    // 显示延长后的线段2
                    HOperatorSet.GenRegionLine(out HObject regionLines2, extendedStartRow2, extendedStartCol2, extendedEndRow2, extendedEndCol2);
                    HOperatorSet.AffineTransRegion(regionLines2, out HObject regionAffineTrans2, homMat2DRotate2, "nearest_neighbor");
                    // HOperatorSet.DispObj(regionAffineTrans2, hw.HalconWindow);
                    HOperatorSet.GetRegionPoints(regionAffineTrans2, out HTuple rows2Points, out HTuple columns2Points);

                    //点1下标
                    HTuple indexMaxPoint1 = 0;
                    HTuple indexMinPoint1 = 0;
                    //点2下标
                    HTuple indexMaxPoint2 = 0;
                    HTuple indexMinPoint2 = 0;
                    //点1
                    HOperatorSet.TupleMax(rows1Points, out HTuple maxPoint1);
                    HOperatorSet.TupleFind(rows1Points, maxPoint1, out indexMaxPoint1);
                    HOperatorSet.TupleMin(rows1Points, out HTuple maxPoint2);
                    HOperatorSet.TupleFind(rows1Points, maxPoint2, out indexMinPoint1);
                    ////点1最小
                    //点2最大
                    HOperatorSet.TupleMax(columns2Points, out HTuple maxPoint3);
                    HOperatorSet.TupleFind(columns2Points, maxPoint3, out indexMaxPoint2);
                    HOperatorSet.TupleMin(columns2Points, out HTuple maxPoint4);
                    HOperatorSet.TupleFind(columns2Points, maxPoint4, out indexMinPoint2);
                    try
                    {
                        //显示交点
                        HOperatorSet.IntersectionLines(rows1Points[indexMinPoint1[indexMinPoint1.Length - 1].D], columns1Points[indexMinPoint1[indexMinPoint1.Length - 1].D], rows1Points[indexMaxPoint1[indexMaxPoint1.Length - 1].D], columns1Points[indexMaxPoint1[indexMaxPoint1.Length - 1].D], rows2Points[indexMinPoint2[indexMinPoint2.Length - 1].D], columns2Points[indexMinPoint2[indexMinPoint2.Length - 1].D], rows2Points[indexMaxPoint2[indexMaxPoint2.Length - 1].D], columns2Points[indexMaxPoint2[indexMaxPoint2.Length - 1].D], out HTuple interRow, out HTuple interColumn, out HTuple isOverlappingInt);
                        HOperatorSet.GenCrossContourXld(out HObject cross, interRow, interColumn, double.Parse(form.pigBox.Text) + 6, new HTuple(45).TupleRad());
                        HOperatorSet.DispObj(cross, hw.HalconWindow);
                        //线段对象
                        HObject lineReg = null;
                        //测量距离对象
                        HTuple distanceMin = null;
                        if (form.comboBox2.Text == "上下排序")
                        {
                            //显示线段
                            HOperatorSet.GenContourPolygonXld(out lineReg, new double[] { point1_Row, interRow }, new double[] { point1_Col, interColumn }); // 修正列坐标
                            HOperatorSet.DispObj(lineReg, hw.HalconWindow);
                            //进行测量
                            HOperatorSet.DistancePp(point1_Row, point1_Col, interRow, interColumn, out distanceMin);
                            //将数据给间距数组
                            linesList[i, 0] = point1_Row;
                            linesList[i, 1] = point1_Col;
                            linesList[i, 2] = interRow;
                            linesList[i, 3] = interColumn;
                        }
                        else if (form.comboBox2.Text == "左右排序")
                        {
                            //显示线段
                            HOperatorSet.GenContourPolygonXld(out lineReg, new double[] { point2_Row, interRow }, new double[] { point2_Col, interColumn }); // 修正列坐标
                            HOperatorSet.DispObj(lineReg, hw.HalconWindow);
                            //进行测量
                            HOperatorSet.DistancePp(point2_Row, point2_Col, interRow, interColumn, out distanceMin);
                            //将数据给间距数组
                            linesList[i, 0] = point2_Row;
                            linesList[i, 1] = point2_Col;
                            linesList[i, 2] = interRow;
                            linesList[i, 3] = interColumn;
                        }
                        HideOutputArrayDistances[i] = distanceMin;
                        //将数据给到界面
                        form.dataGridView1.Rows.Add(i, distanceMin);
                        //显示文本
                        HOperatorSet.AreaCenterPointsXld(lineReg, out HTuple areaArea, out HTuple areaRow, out HTuple areaCol);
                        HideOutputArrayRows[i] = areaRow;
                        HideOutputArrayColumns[i] = areaCol;
                    }
                    catch (Exception e)
                    {
                        throw new Exception("请调整线段排序方式");
                    }
                }
                else
                {
                    throw new Exception("点位找取失败，请调整参数确保2个矩形框中都找到点位信息");
                }
            }
        }


        /// <summary>
        /// 计算偏移量
        /// </summary>
        /// <param name="orientation">方向</param>
        /// <param name="LeftTop_Row">左上角_行</param>
        /// <param name="LeftTop_Col">左上角_列</param>
        /// <param name="RigthButoon_Row">右下角_行</param>
        /// <param name="RigthButoon_Columns">右下角_列</param>
        /// <param name="caliper_width">卡尺宽度</param>
        /// /// <param name="caliperNum">卡尺数量</param>
        /// <param name="L1Measure">输出_高度</param>
        /// <param name="MeasureR1">输出_左上角行</param>
        /// <param name="MeasureC1">输出_左上角行</param>
        /// <param name="offestOfRow">输出_行偏移</param>
        /// <param name="offestOfCol">输出_列偏移</param>
        /// <param name="Phi">输出_角度</param>
        public void Calculate_Office(string orientation,double LeftTop_Row, double LeftTop_Col, double RigthButoon_Row, double RigthButoon_Columns,double caliper_width, int caliperNum, out double L1Measure,out double MeasureR1, out double MeasureC1, out double offestOfRow, out double offestOfCol, out double Phi)
        {
            double LineOfModelR1 = 0;
            double LineOfModelC1 = 0;
            double LineOfModelR2 = 0;
            double LineOfModelC2 = 0;

            if (orientation == "由上向下")
            {
                LineOfModelR1 = (LeftTop_Row + RigthButoon_Row) / 2;
                LineOfModelC1 = LeftTop_Col;
                LineOfModelR2 = (LeftTop_Row + RigthButoon_Row) / 2;
                LineOfModelC2 = RigthButoon_Columns;
                L1Measure = (RigthButoon_Row - LeftTop_Row) / 2;
                MeasureR1 = LineOfModelR1;
                MeasureC1 = LineOfModelC1 + caliper_width;
                offestOfRow = (LineOfModelR2 - LineOfModelR1) / (caliperNum - 1);
                offestOfCol = (LineOfModelC2 - LineOfModelC1 - 2 * caliper_width) / (caliperNum - 1);
                Phi = -((new HTuple(90)).TupleRad());
            }
            else if (orientation == "由下向上")
            {
                LineOfModelR1 = (LeftTop_Row + RigthButoon_Row) / 2;
                LineOfModelC1 = LeftTop_Col;
                LineOfModelR2 = (LeftTop_Row + RigthButoon_Row) / 2;
                LineOfModelC2 = RigthButoon_Columns;
                L1Measure = (RigthButoon_Row - LeftTop_Row) / 2;
                MeasureR1 = LineOfModelR1;
                MeasureC1 = LineOfModelC1 + caliper_width;
                offestOfRow = (LineOfModelR2 - LineOfModelR1) / (caliperNum - 1);
                offestOfCol = (LineOfModelC2 - LineOfModelC1 - 2 * caliper_width) / (caliperNum - 1);
                Phi = ((new HTuple(90)).TupleRad());
            }
            else if (orientation == "由左向右")
            {
                LineOfModelR1 = LeftTop_Row;
                LineOfModelC1 = (LeftTop_Col + RigthButoon_Columns) / 2;
                LineOfModelR2 = RigthButoon_Row;
                LineOfModelC2 = (LeftTop_Col + RigthButoon_Columns) / 2;
                L1Measure = (RigthButoon_Columns - LeftTop_Col) / 2;
                MeasureR1 = LineOfModelR1 + caliper_width;
                MeasureC1 = LineOfModelC1;
                offestOfRow = (LineOfModelR2 - LineOfModelR1 - 2 * caliper_width) / (caliperNum - 1);
                offestOfCol = (LineOfModelC2 - LineOfModelC1) / (caliperNum - 1);
                Phi = ((new HTuple(0)).TupleRad());
            }
            else if (orientation == "由右向左")
            {
                LineOfModelR1 = LeftTop_Row;
                LineOfModelC1 = (LeftTop_Col + RigthButoon_Columns) / 2;
                LineOfModelR2 = RigthButoon_Row;
                LineOfModelC2 = (LeftTop_Col + RigthButoon_Columns) / 2;
                L1Measure = (RigthButoon_Columns - LeftTop_Col) / 2;
                MeasureR1 = LineOfModelR1 + caliper_width;
                MeasureC1 = LineOfModelC1;
                offestOfRow = (LineOfModelR2 - LineOfModelR1 - 2 * caliper_width) / (caliperNum - 1);
                offestOfCol = (LineOfModelC2 - LineOfModelC1) / (caliperNum - 1);
                Phi = -((new HTuple(180)).TupleRad());
            }
            else {
                LineOfModelR1 = 0;
                LineOfModelC1 = 0;
                LineOfModelR2 = 0;
                LineOfModelC2 = 0;
                L1Measure = 0;
                MeasureR1 = 0;
                MeasureC1 = 0;
                offestOfRow = 0;
                offestOfCol = 0;
                Phi = 0;
            }
        }

        public static void Calculate_Office(string orientation, double LeftTop_Row, double LeftTop_Col, double RigthButoon_Row, double RigthButoon_Columns, double caliper_width, int caliperNum, out double L1Measure, out double MeasureR1, out double MeasureC1, out double offestOfRow, out double offestOfCol, out double Phi,bool paper)
        {
            double LineOfModelR1 = 0;
            double LineOfModelC1 = 0;
            double LineOfModelR2 = 0;
            double LineOfModelC2 = 0;

            if (orientation == "由上向下")
            {
                LineOfModelR1 = (LeftTop_Row + RigthButoon_Row) / 2;
                LineOfModelC1 = LeftTop_Col;
                LineOfModelR2 = (LeftTop_Row + RigthButoon_Row) / 2;
                LineOfModelC2 = RigthButoon_Columns;
                L1Measure = (RigthButoon_Row - LeftTop_Row) / 2;
                MeasureR1 = LineOfModelR1;
                MeasureC1 = LineOfModelC1 + caliper_width;
                offestOfRow = (LineOfModelR2 - LineOfModelR1) / (caliperNum - 1);
                offestOfCol = (LineOfModelC2 - LineOfModelC1 - 2 * caliper_width) / (caliperNum - 1);
                Phi = -((new HTuple(90)).TupleRad());
            }
            else if (orientation == "由下向上")
            {
                LineOfModelR1 = (LeftTop_Row + RigthButoon_Row) / 2;
                LineOfModelC1 = LeftTop_Col;
                LineOfModelR2 = (LeftTop_Row + RigthButoon_Row) / 2;
                LineOfModelC2 = RigthButoon_Columns;
                L1Measure = (RigthButoon_Row - LeftTop_Row) / 2;
                MeasureR1 = LineOfModelR1;
                MeasureC1 = LineOfModelC1 + caliper_width;
                offestOfRow = (LineOfModelR2 - LineOfModelR1) / (caliperNum - 1);
                offestOfCol = (LineOfModelC2 - LineOfModelC1 - 2 * caliper_width) / (caliperNum - 1);
                Phi = ((new HTuple(90)).TupleRad());
            }
            else if (orientation == "由左向右")
            {
                LineOfModelR1 = LeftTop_Row;
                LineOfModelC1 = (LeftTop_Col + RigthButoon_Columns) / 2;
                LineOfModelR2 = RigthButoon_Row;
                LineOfModelC2 = (LeftTop_Col + RigthButoon_Columns) / 2;
                L1Measure = (RigthButoon_Columns - LeftTop_Col) / 2;
                MeasureR1 = LineOfModelR1 + caliper_width;
                MeasureC1 = LineOfModelC1;
                offestOfRow = (LineOfModelR2 - LineOfModelR1 - 2 * caliper_width) / (caliperNum - 1);
                offestOfCol = (LineOfModelC2 - LineOfModelC1) / (caliperNum - 1);
                Phi = ((new HTuple(0)).TupleRad());
            }
            else if (orientation == "由右向左")
            {
                LineOfModelR1 = LeftTop_Row;
                LineOfModelC1 = (LeftTop_Col + RigthButoon_Columns) / 2;
                LineOfModelR2 = RigthButoon_Row;
                LineOfModelC2 = (LeftTop_Col + RigthButoon_Columns) / 2;
                L1Measure = (RigthButoon_Columns - LeftTop_Col) / 2;
                MeasureR1 = LineOfModelR1 + caliper_width;
                MeasureC1 = LineOfModelC1;
                offestOfRow = (LineOfModelR2 - LineOfModelR1 - 2 * caliper_width) / (caliperNum - 1);
                offestOfCol = (LineOfModelC2 - LineOfModelC1) / (caliperNum - 1);
                Phi = -((new HTuple(180)).TupleRad());
            }
            else
            {
                LineOfModelR1 = 0;
                LineOfModelC1 = 0;
                LineOfModelR2 = 0;
                LineOfModelC2 = 0;
                L1Measure = 0;
                MeasureR1 = 0;
                MeasureC1 = 0;
                offestOfRow = 0;
                offestOfCol = 0;
                Phi = 0;
            }
        }
        //public void HardRun(HObject HideIntputImage, PreciseCaliper form, HSmartWindowControl hSmartWindowControl, double[] HideIntputArrayRows, double[] HideIntputArrayColumns, double[] HideIntputArrayPhis, List<double> line1counterFrist, List<double> line2counterFrist, List<double> pmaListDouble, ref double[] HideOutputArrayDistances, ref double[,] linesList, ref double[] HideOutputArrayRows, ref double[] HideOutputArrayColumns) 
        //{



        //}
        /// <summary>
        /// 单击点显示点1
        /// </summary>
        /// <param name="row1">点1的行坐标</param>
        /// <param name="col1">点1的列坐标</param>
        //点1的对象存储
        private HObject toPoint1 = null;
        public void ShowPoint1(double row1, double col1)
        {
            try
            {
                if (toPoint1 != null)
                {
                    HOperatorSet.SetColor(hw.HalconWindow, "blue");
                    HOperatorSet.DispObj(toPoint1, hw.HalconWindow);
                }
                HOperatorSet.SetColor(hw.HalconWindow, "red");
                HOperatorSet.GenCrossContourXld(out toPoint1, row1, col1, 5, new HTuple(45).TupleRad());
                HOperatorSet.DispObj(toPoint1, hw.HalconWindow);
                HOperatorSet.SetColor(hw.HalconWindow, "green");
            }
            catch { }
        }
        /// <summary>
        /// 单击点显示点2
        /// </summary>
        /// <param name="row2">点2的行坐标</param>
        /// <param name="col2">点2的列坐标</param>
        private HObject toPoint2;
        public void ShowPoint2(double row2, double col2)
        {
            try
            {
                try
                {
                    if (toPoint2 != null)
                    {
                        HOperatorSet.SetColor(hw.HalconWindow, "green");
                        HOperatorSet.DispObj(toPoint1, hw.HalconWindow);
                    }
                    HOperatorSet.SetColor(hw.HalconWindow, "red");
                    HOperatorSet.GenCrossContourXld(out toPoint2, row2, col2, 5, new HTuple(45).TupleRad());
                    HOperatorSet.DispObj(toPoint1, hw.HalconWindow);
                }
                catch { }
            }
            catch { }
        }
        public static void HardRun(HObject HideIntputImage, PreciseCaliper form, HWindowContentManager drawData, double[] HideIntputArrayRows, double[] HideIntputArrayColumns, double[] HideIntputArrayPhis, List<double> line1counterFrist, List<double> line2counterFrist, List<double> pmaListDouble, ref double[] HideOutputArrayDistances, ref double[,] linesList, ref double[] HideOutputArrayRows, ref double[] HideOutputArrayColumns, HObject rectangle1, HObject rectangle2)
        {
            //if (HideIntputImage == null)
            //{
            //    throw new Exception("当前输入图像为空!");
            //}
            //if (form.comboBox3.Text == "找线功能")
            //{
            //    HardRunLine1ToLine(HideIntputImage, form, hSmartWindowControl, HideIntputArrayRows, HideIntputArrayColumns, HideIntputArrayPhis, line1counterFrist, line2counterFrist, pmaListDouble, ref HideOutputArrayDistances, ref linesList, ref HideOutputArrayRows, ref HideOutputArrayColumns);
            //}
            //else if (form.comboBox3.Text == "找点功能")
            //{
            //    //找点功能方法
            //    HardRunPoint1Point(HideIntputImage, form, hSmartWindowControl, HideIntputArrayRows, HideIntputArrayColumns, HideIntputArrayPhis, line1counterFrist, line2counterFrist, pmaListDouble, ref HideOutputArrayDistances, ref linesList, ref HideOutputArrayRows, ref HideOutputArrayColumns);
            //}

            //找点功能方法
            HardRunPoint1Point(HideIntputImage, form, drawData, HideIntputArrayRows, HideIntputArrayColumns, HideIntputArrayPhis, line1counterFrist, line2counterFrist, pmaListDouble, ref HideOutputArrayDistances, ref linesList, ref HideOutputArrayRows, ref HideOutputArrayColumns,  rectangle1,  rectangle2);
        }
        public HObject rectangle1;
        public HObject rectangle2;
        /// <summary>
        /// 点找点
        /// </summary>
        /// <param name="HideIntputImage"></param>
        /// <param name="form"></param>
        /// <param name="hSmartWindowControl"></param>
        /// <param name="HideIntputArrayRows"></param>
        /// <param name="HideIntputArrayColumns"></param>
        /// <param name="HideIntputArrayPhis"></param>
        /// <param name="line1counterFrist"></param>
        /// <param name="line2counterFrist"></param>
        /// <param name="pmaListDouble"></param>
        /// <param name="HideOutputArrayDistances"></param>
        /// <param name="linesList"></param>
        /// <param name="HideOutputArrayRows"></param>
        /// <param name="HideOutputArrayColumns"></param>
        /// <exception cref="Exception"></exception>
        private static void HardRunPoint1Point(HObject HideIntputImage, PreciseCaliper form, HWindowContentManager drawData, double[] HideIntputArrayRows, double[] HideIntputArrayColumns, double[] HideIntputArrayPhis, List<double> line1counterFrist, List<double> line2counterFrist, List<double> pmaListDouble, ref double[] HideOutputArrayDistances, ref double[,] linesList, ref double[] HideOutputArrayRows, ref double[] HideOutputArrayColumns,HObject rectangle1, HObject rectangle2)
        {  
            //搜索结果 'first','last','all'
            string select = "first";

            // 初始化输出数组
            HideOutputArrayRows = new double[HideIntputArrayColumns.Length];
            HideOutputArrayColumns = new double[HideIntputArrayColumns.Length];
            HideOutputArrayDistances = new double[HideIntputArrayColumns.Length];
            linesList = new double[HideIntputArrayColumns.Length, 4];

            // 获取卡尺宽度、平滑系数和对比度系数
            double caliper_width1 =(double)form.caliper_1_width.Value;
            double caliper_width2 = (double)form.caliper_2_width.Value;
            double sigam1 = (double)form.smoothReg1.Value;
            double sigam2 = (double)form.smoothReg2.Value;
            double threshod1 = (double)form.thresholdMinReg1.Value;
            double threshod2 = (double)form.thresholdMinReg2.Value;

            // 获取卡尺数量
            int caliperNum1 = (int)form.numberReg1.Value;
            int caliperNum2 = (int)form.numberReg2.Value;

            //极性  由明向暗  由暗向明
            string polarity_region1 = form.region_1_direction.SelectedItem.ToString();
            string polarity_region2 = form.region_2_direction.SelectedItem.ToString();
            // 获取极性方向，减少字符串判断
            polarity_region1 = polarity_region1 == "由明向暗" ? "negative" :
                   polarity_region1 == "由暗向明" ? "positive" : "all";

            polarity_region2 = polarity_region2 == "由明向暗" ? "negative" :
                               polarity_region2 == "由暗向明" ? "positive" : "all";

            //获取到矩形框1的信息2个矩形框
            for (int i = 0; i < HideIntputArrayColumns.Length; i++)
            {
                //生成矩形框1
                HObject rectangleNew1 = GenerateRectangle((double)form.re1numberRow.Value, (double)form.re1numberColumn.Value, (double)form.reg1Angle.Value, (double)form.reg1Hegiht.Value, (double)form.reg1Width.Value, ref form.controller.lastParams1,rectangle1);
                if (rectangleNew1 != null)
                {
                    rectangle1= rectangleNew1;
                }

                HObject rectangleNew2 = GenerateRectangle((double)form.re2numberRow.Value, (double)form.re2numberColumn.Value, (double)form.reg2Angle.Value,(double)form.reg2Hegiht.Value, (double)form.reg2Width.Value, ref form.controller.lastParams2,rectangle2);
                if (rectangleNew2 != null)
                {
                    rectangle2 = rectangleNew2;
                }

                //生成第一个跟随的矩形
                HObject ho_RegionAffineTrans1 = UtiyHalcon.MatrixCalculate(rectangle1, HideIntputArrayRows[i], HideIntputArrayColumns[i], HideIntputArrayPhis[i], pmaListDouble[0], pmaListDouble[1], pmaListDouble[2]);

                //生成第二个跟随的矩形
                HObject ho_RegionAffineTrans2 = UtiyHalcon.MatrixCalculate(rectangle2, HideIntputArrayRows[i], HideIntputArrayColumns[i], HideIntputArrayPhis[i], pmaListDouble[0], pmaListDouble[1], pmaListDouble[2]);


                //第一个矩形
                HOperatorSet.GetRegionContour(ho_RegionAffineTrans1, out HTuple rows, out HTuple columns);
                //矩形左上角
                HOperatorSet.TupleMin(rows, out HTuple LeftTop_Row);
                HOperatorSet.TupleMin(columns, out HTuple LeftTop_Col);
                //矩形右下角
                HOperatorSet.TupleMax(rows, out HTuple RigthButoon_Row);
                HOperatorSet.TupleMax(columns, out HTuple RigthButoon_Columns);
                if (form.comboBox4.Text == "开启")
                {
                    drawData.AddRegion(ho_RegionAffineTrans1);
                    //HOperatorSet.DispObj(ho_RegionAffineTrans1, hSmartWindowControl.HalconWindow);
                }

                //******   计算直线角度，根据直线角度及测量方向测算测量矩形的方向phi
                double L1Measure = 0;  //宽度
                double MeasureR1 = 0;  //行
                double MeasureC1 = 0;  //列
                double offestOfRow = 0; //偏移行
                double offestOfCol = 0; //偏移列
                double Phi = 0; //角度
                                //开始计算 

                Calculate_Office(form.controller.recDirection1, LeftTop_Row, LeftTop_Col, RigthButoon_Row, RigthButoon_Columns, caliper_width1, caliperNum1, out L1Measure, out MeasureR1, out MeasureC1, out offestOfRow, out offestOfCol, out Phi,true);

                //点位2的数据集合
                List<double> rowPoint1 = new List<double>();
                List<double> colPoint1 = new List<double>();

                HOperatorSet.GetImageSize(HideIntputImage,out HTuple width,out HTuple height);
                //创建测量模型
                HOperatorSet.GenMeasureRectangle2(MeasureR1, MeasureR1, Phi, L1Measure, caliper_width1, width, height, "nearest_neighbor", out HTuple MeasureHandle);
                //判断是否找点成功
                //if (caliperNum1>int.Parse(form.numberReg1.Value.ToString()))
                //{
                //    throw new Exception("点位找取计算失败");
                //}
                //矩形1的找点
                for (int j = 1; j < caliperNum1 + 1; j++)
                {
                    try
                    {
                        HOperatorSet.TranslateMeasure(MeasureHandle, MeasureR1 + offestOfRow * (j - 1), MeasureC1 + offestOfCol * (j - 1));
                        if (form.comboBox4.Text == "开启")
                        {
                            HOperatorSet.GenRectangle2(out HObject hObject, MeasureR1 + offestOfRow * (j - 1), MeasureC1 + offestOfCol * (j - 1), Phi, L1Measure, caliper_width1);
                            drawData.AddRegion(hObject, "blue");
                        }
                        
                        HOperatorSet.MeasurePos(HideIntputImage, MeasureHandle, sigam1, threshod1, polarity_region1, select, out HTuple RowEdge, out HTuple ColumnEdge, out HTuple Amplitude, out HTuple Distance);
                        //判断是否在区域内
                        HOperatorSet.TestRegionPoint(ho_RegionAffineTrans1, RowEdge, ColumnEdge, out HTuple IsCheck);
                        if (IsCheck.D == 1)
                        {
                            //将数据给到集合中
                            rowPoint1.Add(RowEdge.D);
                            colPoint1.Add(ColumnEdge.D);
                            HOperatorSet.GenCrossContourXld(out HObject cross, RowEdge, ColumnEdge, double.Parse(form.pigBox.Text), new HTuple(45).TupleRad());

                            drawData.AddRegion(cross,"blue");
                        }
                        RowEdge.Dispose();
                        ColumnEdge.Dispose();
                        Amplitude.Dispose();
                        IsCheck.Dispose();
                    }
                    catch
                    {
                        continue;
                    }
                }
                //第二个矩形
                HOperatorSet.GetRegionContour(ho_RegionAffineTrans2, out rows, out  columns);
                //矩形左上角
                HOperatorSet.TupleMin(rows, out LeftTop_Row);
                HOperatorSet.TupleMin(columns, out LeftTop_Col);
                //矩形右下角
                HOperatorSet.TupleMax(rows, out RigthButoon_Row);
                HOperatorSet.TupleMax(columns, out RigthButoon_Columns);

                if (form.comboBox4.Text == "开启")
                {
                    drawData.AddRegion(ho_RegionAffineTrans2, "green");
                }

                //开始计算 
                Calculate_Office(form.controller.recDirection2, LeftTop_Row, LeftTop_Col, RigthButoon_Row, RigthButoon_Columns, caliper_width2, caliperNum2, out L1Measure, out MeasureR1, out MeasureC1, out offestOfRow, out offestOfCol, out Phi, true);

                //创建测量模型
                HOperatorSet.GenMeasureRectangle2(MeasureR1, MeasureR1, Phi, L1Measure, caliper_width2, width, height, "nearest_neighbor", out MeasureHandle);

                //点位2的数据集合
                List<double> rowPoint2 = new List<double>();
                List<double> colPoint2 = new List<double>();
                //判断是否找点成功
                //if (caliperNum2 > int.Parse(form.numberReg1.Value.ToString()))
                //{
                //    throw new Exception("点位找取计算失败");
                //}
                //矩形2的找点
                for (int j = 1; j < caliperNum2 + 1; j++)
                {
                    try
                    {
                        HOperatorSet.TranslateMeasure(MeasureHandle, MeasureR1 + offestOfRow * (j - 1), MeasureC1 + offestOfCol * (j - 1));
                        if (form.comboBox4.Text == "开启")
                        {
                            HOperatorSet.GenRectangle2(out HObject hObject, MeasureR1 + offestOfRow * (j - 1), MeasureC1 + offestOfCol * (j - 1), Phi, L1Measure, caliper_width2);
                            drawData.AddRegion(hObject, "green");
                        }
                        
                        HOperatorSet.MeasurePos(HideIntputImage, MeasureHandle, sigam2, threshod2, polarity_region2, select, out HTuple RowEdge, out HTuple ColumnEdge, out HTuple Amplitude, out HTuple Distance);

                        //判断是否在区域内
                        HOperatorSet.TestRegionPoint(ho_RegionAffineTrans2, RowEdge, ColumnEdge, out HTuple IsCheck);

                        if (IsCheck.D == 1)
                        {
                            //将数据给到集合中
                            rowPoint2.Add(RowEdge.D);
                            colPoint2.Add(ColumnEdge.D);
                            HOperatorSet.GenCrossContourXld(out HObject cross, RowEdge, ColumnEdge, double.Parse(form.pigBox.Text), new HTuple(45).TupleRad());
                            drawData.AddRegion(cross,"green");
                        }
                        RowEdge.Dispose();
                        ColumnEdge.Dispose();
                        Amplitude.Dispose();
                        Distance.Dispose();
                        IsCheck.Dispose();
                    }
                    catch
                    {
                        continue;
                    }
                }
                MeasureHandle.Dispose();
                if (rowPoint1.Count > 0 && colPoint1.Count > 0 && rowPoint2.Count > 0 && colPoint2.Count > 0) // 找到点了
                {
                    // 假设 point1 和 point2 是已知的坐标
                    double point1_Row = 0, point1_Col = 0;
                    double point2_Row = 0, point2_Col = 0;

                    // 获取模板角度
                    double base_phi = pmaListDouble[2]; // 使用基准角度来生成线
                    double template_phi = HideIntputArrayPhis[i]; // 使用模板角度来生成线

                    // 计算最小距离、最大距离和中间距离
                    if (form.comboBox2.Text == "上下排序")
                    {
                        double point1Paper = rowPoint1.Max();
                        double point2Paper = rowPoint2.Min();
                        // 选择点的计算方式
                        if (form.comboBox1.Text == "最小距离")
                        {
                            if (point1Paper < point2Paper)
                            {
                                //计算点1行最大，点2最小就是最小距离
                                point1_Row = rowPoint1.Max();
                                int row1Index = rowPoint1.IndexOf(point1_Row);//下标
                                point1_Col = colPoint1[row1Index];
                                point2_Row = rowPoint2.Min();
                                int row2Index = rowPoint2.IndexOf(point2_Row);//下标
                                point2_Col = colPoint2[row2Index];
                            }
                            else
                            {
                                //计算点1行最大，点2最小就是最小距离
                                point1_Row = rowPoint1.Min();
                                int row1Index = rowPoint1.IndexOf(point1_Row);//下标
                                point1_Col = colPoint1[row1Index];
                                point2_Row = rowPoint2.Max();
                                int row2Index = rowPoint2.IndexOf(point2_Row);//下标
                                point2_Col = colPoint2[row2Index];
                            }
                        }
                        else if (form.comboBox1.Text == "中间距离")
                        {
                            point1_Row = rowPoint1[rowPoint1.Count / 2];
                            point1_Col = colPoint1[colPoint1.Count / 2];
                            point2_Row = rowPoint2[rowPoint2.Count / 2];
                            point2_Col = colPoint2[colPoint2.Count / 2];
                        }
                        else if (form.comboBox1.Text == "最大距离")
                        {
                            if (point1Paper < point2Paper)
                            {
                                //计算点1行最大，点2最小就是最小距离
                                point1_Row = rowPoint1.Min();
                                int row1Index = rowPoint1.IndexOf(point1_Row);//下标
                                point1_Col = colPoint1[row1Index];
                                point2_Row = rowPoint2.Max();
                                int row2Index = rowPoint2.IndexOf(point2_Row);//下标
                                point2_Col = colPoint2[row2Index];
                            }
                            else
                            {
                                //计算点1行最大，点2最小就是最小距离
                                point1_Row = rowPoint1.Max();
                                int row1Index = rowPoint1.IndexOf(point1_Row);//下标
                                point1_Col = colPoint1[row1Index];
                                point2_Row = rowPoint2.Min();
                                int row2Index = rowPoint2.IndexOf(point2_Row);//下标
                                point2_Col = colPoint2[row2Index];
                            }
                        }
                    }
                    else if (form.comboBox2.Text == "左右排序")//计算行坐标
                    {
                        double point1Paper = colPoint1.Max();
                        double point2Paper = colPoint2.Min();
                        // 选择点的计算方式
                        if (form.comboBox1.Text == "最小距离")
                        {
                            if (point1Paper < point2Paper)
                            {
                                //计算点1行最大，点2最小就是最小距离
                                point1_Col = colPoint1.Max();
                                int col1Index = colPoint1.IndexOf(point1_Col);//下标
                                point1_Row = rowPoint1[col1Index];
                                point2_Col = colPoint2.Min();
                                int col2Index = colPoint2.IndexOf(point2_Col);//下标
                                point2_Row = rowPoint2[col2Index];
                            }
                            else
                            {
                                //计算点1行最大，点2最小就是最小距离
                                point1_Col = colPoint1.Min();
                                int col1Index = colPoint1.IndexOf(point1_Col);//下标
                                point1_Row = rowPoint1[col1Index];
                                point2_Col = colPoint2.Max();
                                int col2Index = colPoint2.IndexOf(point2_Col);//下标
                                point2_Row = rowPoint2[col2Index];
                            }
                        }
                        else if (form.comboBox1.Text == "中间距离")
                        {
                            point1_Row = rowPoint1[rowPoint1.Count / 2];
                            point1_Col = colPoint1[colPoint1.Count / 2];
                            point2_Row = rowPoint2[rowPoint2.Count / 2];
                            point2_Col = colPoint2[colPoint2.Count / 2];
                        }
                        else if (form.comboBox1.Text == "最大距离")
                        {
                            if (point1Paper < point2Paper)
                            {
                                //计算点1行最大，点2最小就是最小距离
                                point1_Col = colPoint1.Min();
                                int col1Index = colPoint1.IndexOf(point1_Col);//下标
                                point1_Row = rowPoint1[col1Index];
                                point2_Col = colPoint2.Max();
                                int col2Index = colPoint2.IndexOf(point2_Col);//下标
                                point2_Row = rowPoint2[col2Index];
                            }
                            else
                            {
                                //计算点1行最大，点2最小就是最小距离
                                point1_Col = colPoint1.Max();
                                int col1Index = colPoint1.IndexOf(point1_Col);//下标
                                point1_Row = rowPoint1[col1Index];
                                point2_Col = colPoint2.Min();
                                int col2Index = colPoint2.IndexOf(point2_Col);//下标
                                point2_Row = rowPoint2[col2Index];
                            }

                        }
                    }
                    // 点1沿上下方向生成线
                    double deltaRow = point2_Row - point1_Row;
                    double line1_Start_Row = point1_Row;
                    double line1_Start_Col = point1_Col;
                    double line1_End_Row = point1_Row + Math.Sign(deltaRow) * 100;
                    double line1_End_Col = point1_Col;

                    // 使用模板角度进行旋转生成点2的线段
                    double line2_Start_Row = point2_Row;
                    double line2_Start_Col = point2_Col;
                    double line2_End_Row = point2_Row;
                    double line2_End_Col = point2_Col + Math.Sign(deltaRow) * 100 * Math.Cos(template_phi); // 使用模板角度

                    // 仿射变换当前线段1
                    HOperatorSet.HomMat2dIdentity(out HTuple homMat2DIdentity1);
                    HOperatorSet.HomMat2dRotate(homMat2DIdentity1, HideIntputArrayPhis[i] - pmaListDouble[2], line1_Start_Row, line1_Start_Col, out HTuple homMat2DRotate1);

                    // 计算延长线段1
                    double deltaRow1 = line1_End_Row - line1_Start_Row;
                    double deltaCol1 = line1_End_Col - line1_Start_Col;
                    double extensionFactor1 = 20; // 延长因子，1.5表示延长50%
                    double extendedStartRow1 = line1_Start_Row - extensionFactor1 * deltaRow1;
                    double extendedStartCol1 = line1_Start_Col - extensionFactor1 * deltaCol1;
                    double extendedEndRow1 = line1_End_Row + extensionFactor1 * deltaRow1;
                    double extendedEndCol1 = line1_End_Col + extensionFactor1 * deltaCol1;

                    // 显示延长后的线段1
                    HOperatorSet.GenRegionLine(out HObject regionLines1, extendedStartRow1, extendedStartCol1, extendedEndRow1, extendedEndCol1);
                    HOperatorSet.AffineTransRegion(regionLines1, out HObject regionAffineTrans1, homMat2DRotate1, "constant");
                    HOperatorSet.GetRegionPoints(regionAffineTrans1, out HTuple rows1Points, out HTuple columns1Points);

                    // 仿射变换当前线段2
                    HOperatorSet.HomMat2dIdentity(out HTuple homMat2DIdentity2);
                    HOperatorSet.HomMat2dRotate(homMat2DIdentity2, HideIntputArrayPhis[i] - pmaListDouble[2], line2_Start_Row, line2_Start_Col, out HTuple homMat2DRotate2);

                    // 计算延长线段2
                    double deltaRow2 = line2_End_Row - line2_Start_Row;
                    double deltaCol2 = line2_End_Col - line2_Start_Col;
                    double extensionFactor2 = 20; // 延长因子，1.5表示延长50%
                    double extendedStartRow2 = line2_Start_Row - extensionFactor2 * deltaRow2;
                    double extendedStartCol2 = line2_Start_Col - extensionFactor2 * deltaCol2;
                    double extendedEndRow2 = line2_End_Row + extensionFactor2 * deltaRow2;
                    double extendedEndCol2 = line2_End_Col + extensionFactor2 * deltaCol2;

                    // 显示延长后的线段2
                    HOperatorSet.GenRegionLine(out HObject regionLines2, extendedStartRow2, extendedStartCol2, extendedEndRow2, extendedEndCol2);
                    HOperatorSet.AffineTransRegion(regionLines2, out HObject regionAffineTrans2, homMat2DRotate2, "constant");
                    HOperatorSet.GetRegionPoints(regionAffineTrans2, out HTuple rows2Points, out HTuple columns2Points);

                    // 点1下标
                    HTuple indexMaxPoint1 = 0;
                    HTuple indexMinPoint1 = 0;
                    // 点2下标
                    HTuple indexMaxPoint2 = 0;
                    HTuple indexMinPoint2 = 0;

                    // 点1最大
                    HOperatorSet.TupleMax(rows1Points, out HTuple maxPoint1);
                    HOperatorSet.TupleFind(rows1Points, maxPoint1, out indexMaxPoint1);
                    HOperatorSet.TupleMin(rows1Points, out HTuple maxPoint2);
                    HOperatorSet.TupleFind(rows1Points, maxPoint2, out indexMinPoint1);

                    // 点2最大
                    HOperatorSet.TupleMax(columns2Points, out HTuple maxPoint3);
                    HOperatorSet.TupleFind(columns2Points, maxPoint3, out indexMaxPoint2);
                    HOperatorSet.TupleMin(columns2Points, out HTuple maxPoint4);
                    HOperatorSet.TupleFind(columns2Points, maxPoint4, out indexMinPoint2);
                    HObject cross = null, lineReg = null;
                    HTuple interRow = null, interColumn = null, isOverlappingInt = null;
                    HTuple distanceMin = null, areaArea = null, areaRow = null, areaCol = null;

                    try
                    {
                        // 预计算常用的值，避免重复访问数组
                        double  lastIndex1 = indexMinPoint1[indexMinPoint1.Length - 1].D;
                        double lastIndex2 = indexMinPoint2[indexMinPoint2.Length - 1].D;
                        double lastIndex3 = indexMaxPoint1[indexMaxPoint1.Length - 1].D;
                        double lastIndex4 = indexMaxPoint2[indexMaxPoint2.Length - 1].D;

                        HTuple lastMinPoint1Row = rows1Points[lastIndex1];
                        HTuple lastMinPoint1Col = columns1Points[lastIndex1];
                        HTuple lastMaxPoint1Row = rows1Points[lastIndex3];
                        HTuple lastMaxPoint1Col = columns1Points[lastIndex3];
                        HTuple lastMinPoint2Row = rows2Points[lastIndex2];
                        HTuple lastMinPoint2Col = columns2Points[lastIndex2];
                        HTuple lastMaxPoint2Row = rows2Points[lastIndex4];
                        HTuple lastMaxPoint2Col = columns2Points[lastIndex4];

                        // 显示交点
                        HOperatorSet.IntersectionLines(lastMinPoint1Row, lastMinPoint1Col, lastMaxPoint1Row, lastMaxPoint1Col,
                                                       lastMinPoint2Row, lastMinPoint2Col, lastMaxPoint2Row, lastMaxPoint2Col,
                                                       out  interRow, out  interColumn, out  isOverlappingInt);

                        // 创建交点的十字
                        HOperatorSet.GenCrossContourXld(out  cross, interRow, interColumn, double.Parse(form.pigBox.Text) + 6, new HTuple(45).TupleRad());
                        drawData.AddRegion(cross);
                        // 判断排序方式
                        bool isVerticalSorting = form.comboBox2.Text == "上下排序";
                        bool isHorizontalSorting = form.comboBox2.Text == "左右排序";

                        if (isVerticalSorting || isHorizontalSorting)
                        {
                            double rowStart = isVerticalSorting ? point1_Row : point2_Row;
                            double colStart = isVerticalSorting ? point1_Col : point2_Col;
                            double rowEnd = interRow;
                            double colEnd = interColumn;

                            // 显示线段
                            HOperatorSet.GenContourPolygonXld(out  lineReg, new double[] { rowStart, rowEnd }, new double[] { colStart, colEnd });
                            drawData.AddRegion(lineReg);
                            // 进行测量
                            HOperatorSet.DistancePp(rowStart, colStart, interRow, interColumn, out  distanceMin);

                            // 将数据赋给间距数组
                            if (isVerticalSorting)
                            {
                                linesList[i, 0] = point1_Row;
                                linesList[i, 1] = point1_Col;
                            }
                            else
                            {
                                linesList[i, 0] = point2_Row;
                                linesList[i, 1] = point2_Col;
                            }
                            linesList[i, 2] = interRow;
                            linesList[i, 3] = interColumn;

                            // 存储间距
                            HideOutputArrayDistances[i] = distanceMin;

                            // 获取并显示文本
                            HOperatorSet.AreaCenterPointsXld(lineReg, out  areaArea, out  areaRow, out  areaCol);
                            HideOutputArrayRows[i] = areaRow;
                            HideOutputArrayColumns[i] = areaCol;
                        }
                    }
                    catch (Exception e)
                    {
                        throw new Exception("请调整线段排序方式", e);
                    }
                    finally
                    {
                        // 一次性释放所有 Halcon 对象
                        interRow?.Dispose();
                        interColumn?.Dispose();
                        isOverlappingInt?.Dispose();
                        distanceMin?.Dispose();
                        areaArea?.Dispose();
                        areaRow?.Dispose();
                        areaCol?.Dispose();
                    }
                    // 安全释放所有对象
                    width?.Dispose();
                    height?.Dispose();
                    rows?.Dispose();
                    columns?.Dispose();
                    LeftTop_Row?.Dispose();
                    LeftTop_Col?.Dispose();
                    RigthButoon_Row?.Dispose();
                    RigthButoon_Columns?.Dispose();
                    homMat2DIdentity1?.Dispose();
                    homMat2DRotate1?.Dispose();
                    regionLines1?.Dispose();
                    regionAffineTrans1?.Dispose();
                    rows1Points?.Dispose();
                    columns1Points?.Dispose();
                    homMat2DIdentity2?.Dispose();
                    homMat2DRotate2?.Dispose();
                    regionLines2?.Dispose();
                    regionAffineTrans2?.Dispose();
                    rows2Points?.Dispose();
                    columns2Points?.Dispose();
                    maxPoint1?.Dispose();
                    maxPoint2?.Dispose();
                    maxPoint3?.Dispose();
                    maxPoint4?.Dispose();
                }
                
                else
                {
                    throw new Exception("点位找取失败，请调整参数确保2个矩形框中都找到点位信息");
                }
            }
        }
        public double[] lastParams1 = new double[] { -1, -1, -1, -1, -1 };
        public double[] lastParams2 = new double[] { -1, -1, -1, -1, -1 };
        static HObject GenerateRectangle( double numberRow, double numberColumn, double angle,double height, double width,ref double[] lastParams,HObject reg)
        {
            // 判断参数是否变化
            if (lastParams[0] != numberRow || lastParams[1] != numberColumn ||
                lastParams[2] != angle || lastParams[3] != height || lastParams[4] != width || reg==null)
            {
                lock (lastParams)
                {
                    // 更新缓存参数
                    lastParams[0] = numberRow;
                    lastParams[1] = numberColumn;
                    lastParams[2] = angle;
                    lastParams[3] = height;
                    lastParams[4] = width;   
                }
                // 生成新矩形
                HOperatorSet.GenRectangle2(out HObject rectangle, numberRow, numberColumn, angle, height, width);
                return rectangle;
            }
            return null; // 参数未变化，不生成矩形
        }
      
        /// <summary>
        /// 线找线硬触发
        /// </summary>
        /// <param name="HideIntputImage"></param>
        /// <param name="form"></param>
        /// <param name="hSmartWindowControl"></param>
        /// <param name="HideIntputArrayRows"></param>
        /// <param name="HideIntputArrayColumns"></param>
        /// <param name="HideIntputArrayPhis"></param>
        /// <param name="line1counterFrist"></param>
        /// <param name="line2counterFrist"></param>
        /// <param name="pmaListDouble"></param>
        /// <param name="HideOutputArrayDistances"></param>
        /// <param name="linesList"></param>
        /// <param name="HideOutputArrayRows"></param>
        /// <param name="HideOutputArrayColumns"></param>
        private void HardRunLine1ToLine(HObject HideIntputImage, PreciseCaliper form, HSmartWindowControl hSmartWindowControl, double[] HideIntputArrayRows, double[] HideIntputArrayColumns, double[] HideIntputArrayPhis, List<double> line1counterFrist, List<double> line2counterFrist, List<double> pmaListDouble, ref double[] HideOutputArrayDistances, ref double[,] linesList, ref double[] HideOutputArrayRows, ref double[] HideOutputArrayColumns)
        {
            //    //这里要运行线与线的卡尺测量了
            //    if (HideIntputArrayColumns != null)
            //    {
            //        //卡尺卡的距离
            //        HideOutputArrayDistances = new double[HideIntputArrayColumns.Length];
            //        try
            //        {
            //            linesList = new double[HideIntputArrayColumns.Length, 4];
            //            HideOutputArrayRows = new double[HideIntputArrayColumns.Length];
            //            HideOutputArrayColumns = new double[HideIntputArrayColumns.Length];
            //            for (int i = 0; i < HideIntputArrayColumns.Length; i++)
            //            {
            //                //创建线1的对象
            //                HOperatorSet.GenRegionLine(out HObject hLine1, double.Parse(form.caliper1Row1.Value + ""), double.Parse(form.caliper1Col1.Value + ""), double.Parse(form.caliper1Row2.Value + ""), double.Parse(form.caliper1Col2.Value + ""));
            //                //生成第一条跟随的线
            //                HObject ho_RegionAffineTrans1 = UtiyHalcon.MatrixCalculate(hLine1, HideIntputArrayRows[i], HideIntputArrayColumns[i], HideIntputArrayPhis[i], line1counterFrist[0], line1counterFrist[1], line1counterFrist[2]);
            //                HOperatorSet.GetRegionPoints(ho_RegionAffineTrans1, out HTuple hv_Rows1, out HTuple hv_Columns1);
            //                if (hv_Rows1.Length == 0)
            //                {

            //                    HideOutputArrayDistances[i] = 0;
            //                    continue;
            //                }
            //                //创建计量模型，进行找线
            //                HOperatorSet.CreateMetrologyModel(out HTuple hv_MetrologyHandle);
            //                //增加一个矩形的计量模型
            //                double[] hTuple = new double[] { hv_Rows1.TupleMin(), hv_Columns1.TupleMin(), hv_Rows1.TupleMax(), hv_Columns1.TupleMax() };

            //                HOperatorSet.AddMetrologyObjectGeneric(hv_MetrologyHandle, "line", hTuple, (int)form.line1HeightBox.Value, (int)form.line1Width.Value, double.Parse(form.line1muscle.Value + ""), double.Parse(form.line1contrast.Value + ""), new HTuple(), new HTuple(), out HTuple hv_Index);
            //                string polarity = "";
            //                if (form.line1Combox.SelectedItem.ToString() == "全部")
            //                {
            //                    polarity = "all";
            //                }
            //                if (form.line1Combox.SelectedItem.ToString() == "正极性")
            //                {
            //                    polarity = "negative";
            //                }
            //                if (form.line1Combox.SelectedItem.ToString() == "负极性")
            //                {
            //                    polarity = "positive";
            //                }
            //                if (form.line1Combox.SelectedItem.ToString() == "仅有")
            //                {
            //                    polarity = "uniform";
            //                }
            //                //设置极性
            //                HOperatorSet.SetMetrologyObjectParam(hv_MetrologyHandle, "all", "measure_transition", polarity);
            //                //卡尺的数量
            //                HOperatorSet.SetMetrologyObjectParam(hv_MetrologyHandle, "all", "num_measures", (int)form.line1NumberBox.Value);
            //                //卡尺卡的数量 接受的结果数
            //                HOperatorSet.SetMetrologyObjectParam(hv_MetrologyHandle, "all", "num_instances", 1);
            //                //bilinear
            //                HOperatorSet.SetMetrologyObjectParam(hv_MetrologyHandle, "all", "measure_interpolation", "bicubic");
            //                HOperatorSet.SetMetrologyObjectParam(hv_MetrologyHandle, "all", "measure_select", "all");
            //                //最小分数
            //                HOperatorSet.SetMetrologyObjectParam(hv_MetrologyHandle, "all", "min_score", double.Parse(form.line1small.Value.ToString()));
            //                //开始抓
            //                HOperatorSet.ApplyMetrologyModel(HideIntputImage, hv_MetrologyHandle);
            //                HOperatorSet.GetMetrologyObjectMeasures(out HObject ho_Contours, hv_MetrologyHandle, "all", "all",
            //                            out HTuple hv_Row, out HTuple hv_Column);
            //                HOperatorSet.GenContourPolygonXld(out HObject regionLines1, new double[] { hv_Row[0].D, hv_Row[hv_Row.Length - 1].D }, new double[] { hv_Column[0].D, hv_Column[hv_Column.Length - 1].D });
            //                if (form.comboBox4.Text == "开启")
            //                {
            //                    HOperatorSet.DispObj(regionLines1, hSmartWindowControl.HalconWindow);
            //                    HOperatorSet.SetColor(hSmartWindowControl.HalconWindow, "blue");
            //                    HOperatorSet.GenCrossContourXld(out HObject Corss1, hv_Row, hv_Column, 10, new HTuple(45).TupleRad());
            //                    HOperatorSet.DispObj(Corss1, hSmartWindowControl.HalconWindow);
            //                    HOperatorSet.SetColor(hSmartWindowControl.HalconWindow, "green");
            //                }
            //                //创建线2的对象
            //                HOperatorSet.GenRegionLine(out HObject hLine2, double.Parse(form.caliper2Row1.Value + ""), double.Parse(form.caliper2Col1.Value + ""), double.Parse(form.caliper2Row2.Value + ""), double.Parse(form.caliper2Col2.Value + ""));
            //                //生成第一条跟随的线
            //                HObject ho_RegionAffineTrans2 = UtiyHalcon.MatrixCalculate(hLine2, HideIntputArrayRows[i], HideIntputArrayColumns[i], HideIntputArrayPhis[i], line2counterFrist[0], line2counterFrist[1], line2counterFrist[2]);
            //                HOperatorSet.GetRegionPoints(ho_RegionAffineTrans2, out HTuple hv_Rows2, out HTuple hv_Columns2);
            //                if (hv_Rows2.Length == 0)
            //                {
            //                    continue;
            //                }
            //                //创建计量模型，进行找线
            //                HOperatorSet.CreateMetrologyModel(out HTuple hv_MetrologyHandle2);
            //                //增加一个矩形的计量模型
            //                double[] hTuple2 = new double[] { hv_Rows2.TupleMin(), hv_Columns2.TupleMin(), hv_Rows2.TupleMax(), hv_Columns2.TupleMax() };

            //                HOperatorSet.AddMetrologyObjectGeneric(hv_MetrologyHandle2, "line", hTuple2, (int)form.line2HeightBox.Value, (int)form.line2Width.Value, double.Parse(form.line2muscle.Value + ""), double.Parse(form.line2contrast.Value + ""), new HTuple(), new HTuple(), out HTuple hv_Index2);
            //                string polarity2 = "";
            //                if (form.line2Combox.SelectedItem.ToString() == "全部")
            //                {
            //                    polarity2 = "all";
            //                }
            //                if (form.line2Combox.SelectedItem.ToString() == "正极性")
            //                {
            //                    polarity2 = "negative";
            //                }
            //                if (form.line2Combox.SelectedItem.ToString() == "负极性")
            //                {
            //                    polarity2 = "positive";
            //                }
            //                if (form.line2Combox.SelectedItem.ToString() == "仅有")
            //                {
            //                    polarity2 = "uniform";
            //                }
            //                //设置极性
            //                HOperatorSet.SetMetrologyObjectParam(hv_MetrologyHandle2, "all", "measure_transition", polarity2);
            //                //卡尺的数量
            //                HOperatorSet.SetMetrologyObjectParam(hv_MetrologyHandle2, "all", "num_measures", (int)form.line2NumberBox.Value);
            //                //卡尺卡的数量 接受的结果数
            //                HOperatorSet.SetMetrologyObjectParam(hv_MetrologyHandle2, "all", "num_instances", 1);
            //                //bilinear
            //                HOperatorSet.SetMetrologyObjectParam(hv_MetrologyHandle2, "all", "measure_interpolation", "bicubic");
            //                HOperatorSet.SetMetrologyObjectParam(hv_MetrologyHandle2, "all", "measure_select", "all");
            //                //最小分数
            //                HOperatorSet.SetMetrologyObjectParam(hv_MetrologyHandle2, "all", "min_score", double.Parse(form.line2small.Value.ToString()));
            //                //开始抓
            //                HOperatorSet.ApplyMetrologyModel(HideIntputImage, hv_MetrologyHandle2);
            //                HOperatorSet.GetMetrologyObjectMeasures(out HObject ho_Contours2, hv_MetrologyHandle2, "all", "all",
            //                            out HTuple hv_Row2, out HTuple hv_Column2);
            //                HOperatorSet.GenContourPolygonXld(out HObject regionLines2, new double[] { hv_Row2[0].D, hv_Row2[hv_Row2.Length - 1].D }, new double[] { hv_Column2[0].D, hv_Column2[hv_Column2.Length - 1].D });
            //                if (form.comboBox4.Text == "开启")
            //                {
            //                    HOperatorSet.DispObj(regionLines2, hSmartWindowControl.HalconWindow);
            //                    HOperatorSet.SetColor(hSmartWindowControl.HalconWindow, "blue");
            //                    HOperatorSet.GenCrossContourXld(out HObject Corss2, hv_Row2, hv_Column2, 10, new HTuple(45).TupleRad());
            //                    HOperatorSet.DispObj(Corss2, hSmartWindowControl.HalconWindow);
            //                    HOperatorSet.SetColor(hSmartWindowControl.HalconWindow, "green");
            //                }
            //                //计算线到线之间的距离  distance_ss    distanceMin:2条线段最小距离       distanceMax:2条线段最大距离
            //                HOperatorSet.DistanceSs(hv_Row[0], hv_Column[0], hv_Row[hv_Row.Length - 1], hv_Column[hv_Column.Length - 1], hv_Row2[0], hv_Column2[0], hv_Row2[hv_Row2.Length - 1], hv_Column2[hv_Column2.Length - 1], out HTuple distanceMin, out HTuple distanceMax);
            //                double distancesss = 0;
            //                //if (form.comboBox5.Text == "最大距离")
            //                //{
            //                //    distancesss = distanceMax;
            //                //}
            //                //else if (form.comboBox5.Text == "最小距离")
            //                //{
            //                //    distancesss = distanceMin;
            //                //}
            //                HideOutputArrayDistances[i] = distancesss;
            //                //将数据给间距数组
            //                linesList[i, 0] = hv_Row[0];
            //                linesList[i, 1] = hv_Column[0];
            //                linesList[i, 2] = hv_Row2[0];
            //                linesList[i, 3] = hv_Column2[0];
            //                //生成一条测试的线段
            //                HObject hObjectLine = null;//亚像素轮廓
            //                HObject hObjectLineCenter = null;//线区域
            //                if (form.comboBox1.Text == "第一点")
            //                {
            //                    if (form.comboBox2.Text == "行排序")
            //                    {
            //                        if (hv_Row != null && hv_Row2 != null)
            //                        {
            //                            HOperatorSet.GenContourPolygonXld(out hObjectLine, new double[] { hv_Row[0], hv_Row2[0] }, new double[] { hv_Column[0], hv_Column[0] });
            //                            HOperatorSet.GenRegionLine(out hObjectLineCenter, hv_Row[0], hv_Column[0], hv_Row2[0], hv_Column[0]);
            //                            HOperatorSet.DispObj(hObjectLine, hSmartWindowControl.HalconWindow);
            //                        }

            //                    }
            //                    else if (form.comboBox2.Text == "列排序")
            //                    {
            //                        if (hv_Row != null && hv_Row2 != null)
            //                        {
            //                            HOperatorSet.GenContourPolygonXld(out hObjectLine, new double[] { hv_Row[0], hv_Row[0] }, new double[] { hv_Column[0], hv_Column2[0] });
            //                            HOperatorSet.GenRegionLine(out hObjectLineCenter, hv_Row[0], hv_Column[0], hv_Row[0], hv_Column2[0]);
            //                            HOperatorSet.DispObj(hObjectLine, hSmartWindowControl.HalconWindow);
            //                        }
            //                    }
            //                }
            //                else if (form.comboBox1.Text == "中间点")
            //                {
            //                    if (form.comboBox2.Text == "行排序")
            //                    {
            //                        if (hv_Row != null && hv_Row2 != null)
            //                        {
            //                            double columnCount = ((hv_Column[hv_Column.Length - 1].D - hv_Column[0]) / 2) + hv_Column[0].D;
            //                            HOperatorSet.GenContourPolygonXld(out hObjectLine, new double[] { hv_Row[0], hv_Row2[0] }, new double[] { columnCount, columnCount });
            //                            HOperatorSet.GenRegionLine(out hObjectLineCenter, hv_Row[0], columnCount, hv_Row2[0], columnCount);
            //                            HOperatorSet.DispObj(hObjectLine, hSmartWindowControl.HalconWindow);
            //                        }

            //                    }
            //                    else if (form.comboBox2.Text == "列排序")
            //                    {
            //                        if (hv_Row != null && hv_Row2 != null)
            //                        {
            //                            double columnCount = ((hv_Row[hv_Row.Length - 1].D - hv_Row[0].D) / 2) + hv_Row[0].D;
            //                            HOperatorSet.GenContourPolygonXld(out hObjectLine, new double[] { columnCount, columnCount }, new double[] { hv_Column[0], hv_Column2[0] });
            //                            HOperatorSet.GenRegionLine(out hObjectLineCenter, columnCount, hv_Column[0], columnCount, hv_Column2[0]);
            //                            HOperatorSet.DispObj(hObjectLine, hSmartWindowControl.HalconWindow);
            //                        }
            //                    }
            //                }
            //                else if (form.comboBox1.Text == "末端点")
            //                {
            //                    if (form.comboBox2.Text == "行排序")
            //                    {
            //                        if (hv_Row != null && hv_Row2 != null)
            //                        {
            //                            HOperatorSet.GenContourPolygonXld(out hObjectLine, new double[] { hv_Row[hv_Row.Length - 1], hv_Row2[hv_Row2.Length - 1] }, new double[] { hv_Column[hv_Column.Length - 1], hv_Column[hv_Column.Length - 1] });
            //                            HOperatorSet.GenRegionLine(out hObjectLineCenter, hv_Row[hv_Row.Length - 1], hv_Column[hv_Column.Length - 1], hv_Row2[hv_Row2.Length - 1], hv_Column[hv_Column.Length - 1]);
            //                            HOperatorSet.DispObj(hObjectLine, hSmartWindowControl.HalconWindow);
            //                        }
            //                    }
            //                    else if (form.comboBox2.Text == "列排序")
            //                    {
            //                        if (hv_Row != null && hv_Row2 != null)
            //                        {
            //                            HOperatorSet.GenContourPolygonXld(out hObjectLine, new double[] { hv_Row[hv_Row.Length - 1], hv_Row[hv_Row.Length - 1] }, new double[] { hv_Column[hv_Column.Length - 1], hv_Column2[hv_Column2.Length - 1] });
            //                            HOperatorSet.GenRegionLine(out hObjectLineCenter, hv_Row[hv_Row.Length - 1], hv_Column[hv_Column.Length - 1], hv_Row[hv_Row.Length - 1], hv_Column2[hv_Column2.Length - 1]);
            //                            HOperatorSet.DispObj(hObjectLine, hSmartWindowControl.HalconWindow);
            //                        }
            //                    }
            //                }
            //                //显示文本
            //                HOperatorSet.AreaCenter(hObjectLineCenter, out HTuple area3, out HTuple rowLine3, out HTuple columnLine3);
            //                HideOutputArrayRows[i] = rowLine3;
            //                HideOutputArrayColumns[i] = columnLine3;
            //            }
            //        }
            //        catch (Exception ex)
            //        {
            //            throw new Exception("线段1抓取失败" + ex.Message);
            //        }
            //    }
            //}
        }
    }
}
